Reputation: 450
I am having a gridview with some columns and a template field column that contains a button and I want to call a procedure on button click, however I want to pass a value of a column to the procedure but I am getting an error, here is the action listener of the button: (column name in the gridview is team_ID) error: Databinding methods such as Eval(), XPath(), and Bind() can only be used in the context of a databound control. error line: 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();
}
Upvotes: 0
Views: 1678
Reputation: 83356
First, to handle a button what was clicked in an TemplateField, you'll want to subscribe to the RowCommand
method:
<asp:GridView runat="server" ID="gv" OnRowCommand="yourMethod">
You can have multiple buttons in your grid and surmise which caused the click with the CommandName
property. The code below shows this, as well as how to get the row of the button that was clicked, and retrieve other controls from that row so you can get their values.
<asp:TemplateField>
<ItemTemplate>
<asp:Button CommandName="yourButtonName" runat="server" />
Code Behind
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;
}
}
Upvotes: 2