【问题标题】:accessing data of a GridView on button click在按钮单击时访问 GridView 的数据
【发布时间】:2012-01-27 18:29:30
【问题描述】:

我有一个带有一些列的 gridview 和一个包含按钮的模板字段列,我想在单击按钮时调用一个过程,但是我想将一个列的值传递给该过程,但我收到了一个错误,这里是按钮的动作监听器:(gridview中的列名是team_ID) 错误:Eval()、XPath() 和 Bind() 等数据绑定方法只能在数据绑定控件的上下文中使用。 错误行:int team_ID = Convert.ToInt32(Eval("team_ID"));

protected void Button1_Click(object sender, EventArgs e)
    {
        string connStr = ConfigurationManager.ConnectionStrings["MyDbConn"].ToString();
        SqlConnection conn = new SqlConnection(connStr);

        SqlCommand cmd = new SqlCommand("join_team", conn);
        cmd.CommandType = CommandType.StoredProcedure;
        int team_ID = Convert.ToInt32(Eval("team_ID"));
        string email = Session["email"].ToString();
        cmd.Parameters.Add(new SqlParameter("@team_ID", team_ID));
        cmd.Parameters.Add(new SqlParameter("@myemail", email));
        conn.Open();
        cmd.ExecuteNonQuery();
        conn.Close();

    }

【问题讨论】:

    标签: c# asp.net mysql visual-studio-2010


    【解决方案1】:

    首先,要处理在 TemplateField 中单击的按钮,您需要订阅 RowCommand 方法:

    <asp:GridView runat="server" ID="gv" OnRowCommand="yourMethod">
    

    您的网格中可以有多个按钮,并使用CommandName 属性推测导致点击的原因。下面的代码展示了这一点,以及如何获取被点击按钮所在的行,并从该行中检索其他控件,以便获取它们的值。

    <asp:TemplateField>
          <ItemTemplate>
                <asp:Button CommandName="yourButtonName" runat="server" />
    

    代码背后

    protected void yourMethod(object sender, GridViewCommandEventArgs e) {
        if (e.CommandName == "yourButtonName") {
    
            GridViewRow row = (GridViewRow)(((Button)e.CommandSource).NamingContainer);
    
            TextBox someTextBox = row.FindControl("tb") as TextBox;
            string textValue = someTextBox.Text;
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-05-26
      • 1970-01-01
      • 1970-01-01
      • 2015-09-28
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多