【问题标题】:How to get cell value if I know column name in gridview如果我知道gridview中的列名,如何获取单元格值
【发布时间】:2013-07-28 18:13:32
【问题描述】:

我有这样的“GridView1”和“label1”:

ID___________NAME___________SELECT

1 --------- NAME1 --------- button

2 --------- NAME2 --------- button

3 --------- NAME3 --------- button

4 --------- NAME4 --------- button

lable1 = null

如果我点击 SELECT 列中的任何按钮,我想将我选择的人的 ID 显示到 label1,例如如果我点击第一行的按钮,它应该显示:

label1: You have selected people with ID = 1

我该怎么做?

【问题讨论】:

  • 有回发还是没有回发?
  • @RameezAhmedSayad:回复说。
  • @RonaldinhoState 你能告诉我们你是如何处理按钮点击事件的吗??
  • 有不同的方法......你可以尝试一种。先用谷歌搜索一下
  • @AmitSingh:如果我知道如何处理它,那么我不应该问这个问题 LOL,j/k 你是什么意思?

标签: asp.net gridview datatable


【解决方案1】:

您可以使用以下源代码

<asp:ImageButton ID="btnConfirm" runat="server" CommandArgument='<%# Container.DataItemIndex %>' OnClick="btnConfirm_Click"  />

还有这个cs代码


protected void btnHClear_Click(object sender, ImageClickEventArgs e)
{
    label1.Text = GridView1.Rows[Convert.ToInt32(((ImageButton)sender).CommandArgument.ToString())].Cells[1].Text;
}

【讨论】:

  • 应该是 [0] 因为我需要 ID 列,它只是 Button 而不是 ImageButton。谢谢大家! :))
  • 节省了一天 :) 谢谢
【解决方案2】:

在 gridview SelectedIndexChanged 事件中,您可以获得如下 id

var id = GridView1.DataKeys[row.RowIndex].Values[0];

但您需要在 aspx 页面的网格视图标记中设置 DataKeyNames="ID"

现在通过使用 id 值可以设置标签文本。

Label1.Text = "You have selected people with ID = " +id;

【讨论】:

    【解决方案3】:

    如您所见,使用您的 GridView,仅意味着 3 列。

    对于具有按钮的 SELECT 列,将按钮的 CommandName 属性设置为 Select。

    <asp:TemplateField>
        <ItemTemplate>
        <asp:Button ID="selectBTN" runat="server" CommandName="Select" />
        </ItemTemplate>
    </asp:TemplateField>
    

    为 GridView 设置 OnSelectedIndexChanged 事件。

    <asp:GridView ID="GridView1" DataKeyNames="CustomerID"  runat="server"     
          OnSelectedIndexChanged="GridView1_Selected" >
    

    现在在事件处理程序中将标签值设置为:

     protected void GridView1_Selected(object sender, System.EventArgs e)
            {
                GridViewRow row = GridView1.SelectedRow; // Get the selected row 
               // Get the Column value, Cells[0] represents first column: ID ,
               //Cells[1] represents second column : NAME, etc...
                labelName.Text = row.Cells[0].Text;   
    
            }
    

    【讨论】:

      【解决方案4】:

      请看以下链接:

      http://www.c-sharpcorner.com/forums/thread/153329/changing-gridview-row-color-on-row-command.aspx

      在这部分你必须改变的IN

      if (e.CommandName == "Select")
          {            
              int rowIndex = Convert.ToInt32(e.CommandArgument);
              GridViewRow row = gviewRetailers.Rows[index];
              Label1.Text =  "You have selected people with ID = " + row.Cells[0].Text;
          }
      

      谢谢, 希特什

      【讨论】:

        猜你喜欢
        • 2021-06-28
        • 2015-02-15
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-02-04
        • 1970-01-01
        • 2023-02-02
        相关资源
        最近更新 更多