GridViewRowCommand无法找到标题行文本框值

时间:2016-01-26 18:30:01

标签: c# asp.net gridview templatefield header-row

我正在尝试使用gridview标头模板插入到sql表中,在gridview rowcommand下我试图找到该控件并且它无法检索该值。

protected void GridView1_RowCommand1(object sender, GridViewCommandEventArgs e)
{
    if (e.CommandName == "Insert")
    {
        string NetWeightConnectionStrings = ConfigurationManager.ConnectionStrings["NetWeightConnectionString"].ToString();
        string query = "INSERT INTO [Net Weight Tracking] ([Date])VALUES (@Date)";
        using (SqlConnection sqlConn = new SqlConnection(NetWeightConnectionStrings))
        using (SqlCommand cmd = new SqlCommand(query, sqlConn))
        {
            String Date = ((TextBox)GridV1.HeaderRow.FindControl("TextBox31")).Text;
            cmd.Parameters.Add("@Date", SqlDbType.DateTime).Value = DateTime.ParseExact(((TextBox)GridV1.HeaderRow.FindControl("TextBox31")).Text, "dd/MM/yyyy", null);
            sqlConn.Open();
            DataTable dt = new DataTable();
            dt.Load(cmd.ExecuteReader());
            GridV1.DataSource = dt;
            GridV1.DataBind();
            sqlConn.Close();
        }
    }
}

非常感谢任何帮助

1 个答案:

答案 0 :(得分:0)

您可以尝试RowDataBound事件来获取标题模板控件。

protected void GridView1__RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.Header)
        {
             TextBox txtControl = (TextBox)e.Row.FindControl("TextBox31");
        }
     }

编辑1

从为GridView标记共享的链接,Tex​​tBox31不在HeaderItemTemplate中,它在EditItemTemplate中。这就是原因,你无法找到文本框。

 <EditItemTemplate>
                        <asp:TextBox ID="TextBox31" runat="server" Text='<%# Bind("Field4") %>'></asp:TextBox>
                    </EditItemTemplate>