0

i am trying to insert into sql table using gridview header template, under the gridview rowcommand i am trying to find the control and it is not able to retrieve the value.

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();
        }
    }
}

any help is much appreciated

Henk van Boeijen
  • 7,357
  • 6
  • 32
  • 42
Beast Mode
  • 27
  • 1
  • 7

1 Answers1

0

You can try the RowDataBound Event to get the header template controls.

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

EDIT 1

From the link shared for the GridView Mark up, TextBox31 is not in the HeaderItemTemplate, it is in EditItemTemplate. That would be the reason, you are not able to find the textbox.

 <EditItemTemplate>
                        <asp:TextBox ID="TextBox31" runat="server" Text='<%# Bind("Field4") %>'></asp:TextBox>
                    </EditItemTemplate>
Abhinav Galodha
  • 9,293
  • 2
  • 31
  • 41