gpt4 book ai didi

c# - 单击按钮时访问 GridView 的数据

转载 作者:行者123 更新时间:2023-11-29 09:01:00 24 4
gpt4 key购买 nike

我有一个带有一些列的 GridView 和一个包含按钮的模板字段列,我想在单击按钮时调用一个过程,但是我想将列的值传递给该过程,但我收到错误,这里是按钮的 Action 监听器:(gridview中的列名是team_ID)错误:Eval()、XPath() 和 Bind() 等数据绑定(bind)方法只能在数据绑定(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();

}

最佳答案

首先,要处理在 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;
}
}

关于c# - 单击按钮时访问 GridView 的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8632267/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com