locked
Retrieve Control Values from within GridView cells RRS feed

  • Question

  • User2015884762 posted

    Hi

    This is my GridView code

    protected void GridView5_RowDataBound(object sender, GridViewRowEventArgs e)
            {
                CheckColumnsMatch();
                int number_row_inGD = GridView5.Rows.Count;
                int number_columns_inGD = GridView5.Columns.Count;
                if (e.Row.RowType == DataControlRowType.DataRow)
                {
                    for (int column = 3; column < GridView5.Columns.Count; column++)
                    {
                        Label txtTargetvalue = new Label();
                        txtTargetvalue.CssClass = "form-control-plaintext";
                        txtTargetvalue.ID = "txtTargetvalue";
    
                        //create hidden field
                        TextBox pallet_qty_fullday = new TextBox();
                        TextBox pallet_qty_shift1 = new TextBox();
                        TextBox pallet_qty_shift2 = new TextBox();
    
                        TextBox txtTargetvalue_shift1 = new TextBox();
                        TextBox txtTargetvalue_shift2 = new TextBox();
                        // end of hidden field
    
                        e.Row.Cells[column].Controls.Add(txtTargetvalue);
    
                        e.Row.Cells[column].Controls.Add(txtTargetvalue_shift1);
                        txtTargetvalue_shift1.Visible = false;
    
                        e.Row.Cells[column].Controls.Add(txtTargetvalue_shift2);
                        txtTargetvalue_shift2.Visible = false;
    
                        e.Row.Cells[column].Controls.Add(pallet_qty_fullday);
                        pallet_qty_fullday.Visible = false;
    
                        e.Row.Cells[column].Controls.Add(pallet_qty_shift1);
                        pallet_qty_shift1.Visible = false;
    
                        e.Row.Cells[column].Controls.Add(pallet_qty_shift2);
                        pallet_qty_shift2.Visible = false;
    
                        for (int row = 0; row <= GridView5.Rows.Count; row++)
                        {
                            bool tgtDataISNumber;
    
                            tgtDataISNumber = Check_TgtData_Type(importcleandata.Rows[row][column - 1]);
    
                            if(tgtDataISNumber == true)
                            {
                                double targetData_fullday = Convert.ToDouble(importcleandata.Rows       [row][column - 1]);
                                double palletteqty_fullday = (targetData_fullday * 1000) / 6000;
                                double pallettqty_pershift = palletteqty_fullday / 2;
                                double targetData_pershift = targetData_fullday / 2;
                                txtTargetvalue_shift1.Text = targetData_pershift.ToString();
                                txtTargetvalue_shift2.Text = targetData_pershift.ToString();
    
                                pallet_qty_fullday.Text = palletteqty_fullday.ToString();
                                pallet_qty_shift1.Text = pallettqty_pershift.ToString();
                                pallet_qty_shift2.Text = pallettqty_pershift.ToString();
    
                                
                                txtTargetvalue.Text = importcleandata.Rows[row][column - 1].ToString();
                                
                                txtTargetvalue.Attributes.Add("OnClick", "PrintDetails(" + (row + 1) + "," + column + ")");
                              
    
    
    
                }
                            else
                            {
                                string targetData_code = importcleandata.Rows[row][column - 1].ToString();
                                txtTargetvalue.Text = importcleandata.Rows[row][column - 1].ToString();
                                txtTargetvalue.Attributes.Add("OnClick", "PrintDetails(" + (row + 1) + "," + column + ")");
                                
                            }
    
                           
                        }
                    }
                    
                }
                
    
            }

    and this is the code during button click that I need to retrieve the values from the created gridview.

    protected void Submit_To_DB_Click(object sender, EventArgs e)
            {
                //function call to create Data Table
                MakeDataTable_beforesubmit();
            }
    private void MakeDataTable_beforesubmit()
            {
                DataColumn column;
                DataRow row;
    
                // Create new DataColumn, set DataType, 
                // ColumnName and add to DataTable.    
                column = new DataColumn();
                column.DataType = System.Type.GetType("System.String");
                column.ColumnName = "MachineName";
                column.ReadOnly = true;
                column.Unique = true;
                // Add the Column to the DataColumnCollection.
                submittodb_datatable.Columns.Add(column);
    
                column = new DataColumn();
                column.DataType = System.Type.GetType("System.DateTime");
                column.ColumnName = "Target_Date";
                column.ReadOnly = true;
                column.Unique = true;
                // Add the Column to the DataColumnCollection.
                submittodb_datatable.Columns.Add(column);
    
                column = new DataColumn();
                column.DataType = System.Type.GetType("System.Int32");
                column.ColumnName = "Target_data_FullDay";
                column.ReadOnly = true;
                // Add the Column to the DataColumnCollection.
                submittodb_datatable.Columns.Add(column);
    
                column = new DataColumn();
                column.DataType = System.Type.GetType("System.Int32");
                column.ColumnName = "Target_data_Shift1";
                column.ReadOnly = true;
                // Add the Column to the DataColumnCollection.
                submittodb_datatable.Columns.Add(column);
    
                column = new DataColumn();
                column.DataType = System.Type.GetType("System.Int32");
                column.ColumnName = "Target_data_Shift2";
                column.ReadOnly = true;
                // Add the Column to the DataColumnCollection.
                submittodb_datatable.Columns.Add(column);
    
                column = new DataColumn();
                column.DataType = System.Type.GetType("System.Int32");
                column.ColumnName = "Pallette_Qty_FullDay";
                column.ReadOnly = true;
                // Add the Column to the DataColumnCollection.
                submittodb_datatable.Columns.Add(column);
    
                column = new DataColumn();
                column.DataType = System.Type.GetType("System.Int32");
                column.ColumnName = "Pallette_Qty_Shift1";
                column.ReadOnly = true;
                // Add the Column to the DataColumnCollection.
                submittodb_datatable.Columns.Add(column);
    
                column = new DataColumn();
                column.DataType = System.Type.GetType("System.Int32");
                column.ColumnName = "Pallette_Qty_Shift2";
                column.ReadOnly = true;
                // Add the Column to the DataColumnCollection.
                submittodb_datatable.Columns.Add(column);
    
                column = new DataColumn();
                column.DataType = System.Type.GetType("System.String");
                column.ColumnName = "Job_Name1";
                column.ReadOnly = true;
                // Add the Column to the DataColumnCollection.
                submittodb_datatable.Columns.Add(column);
    
                column = new DataColumn();
                column.DataType = System.Type.GetType("System.String");
                column.ColumnName = "Job_Name2";
                column.ReadOnly = true;
                // Add the Column to the DataColumnCollection.
                submittodb_datatable.Columns.Add(column);
    
                int header_column_beforedatevalue = 2;
    
                for (int i = 3; i <= GridView5.HeaderRow.Cells.Count; i++)
                {
                    row = submittodb_datatable.NewRow();
                    row["MachineName"] = "Susi 1ax";
    
                    //GridView1.Rows[i].Cells[5].Text
                    row["Target_Date"] = GridView5.HeaderRow.Cells[i].Text;
    
                    int row_count = GridView5.Rows.Count;
    
                    Label tgtvalue = new Label();
                    tgtvalue = (Label)GridView5.Rows[1].Cells[i].FindControl("txtTargetvalue");
                    string Ques1 = tgtvalue.Text;
                    row["Target_data_FullDay"] = tgtvalue.Text;
    
                        row["Target_data_Shift1"] = "test";
                        row["Target_data_Shift2"] = "test";
                    row["Pallette_Qty_FullDay"] = "test";
                    row["Pallette_Qty_Shift1"] = "test";
                    row["Pallette_Qty_Shift2"] = "test";
    
    
    
                    row["Job_Name1"] = "test";
                    row["Job_Name2"] = "test";
                    submittodb_datatable.Rows.Add(row);
                }

    In each of the GridView Cell, there are about 6 controls, 1 Label and 5 textboxes. I would need to retrieve those value, however, I am getting null when I do this tgtvalue = (Label)GridView5.Rows[1].Cells[i].FindControl("txtTargetvalue");

    In fact when I tried debugging, the count of controls in the cell actually returned 0. How can I solve this.

    Tuesday, March 12, 2019 6:32 AM

Answers

  • User-893317190 posted

    Hi targetData_fullday,

    If so , I suggest you could add a control that could store mutiple values , such as dropdownlist , gridview and so on.

    Here  I make a small sample with dropdown list.

     <form id="form1" runat="server">
            <asp:GridView ID="GridView1" DataKeyNames="InfoId" runat="server" OnRowDataBound="GridView1_RowDataBound" AutoGenerateSelectButton="true" OnSelectedIndexChanged="GridView1_SelectedIndexChanged">
                <Columns>
                    <asp:TemplateField>
                        <ItemTemplate>
                            <asp:DropDownList ID="DropDownList1" runat="server" Visible="false"></asp:DropDownList>
                            
                        </ItemTemplate>
                        
                    </asp:TemplateField>
                  
                </Columns>
            </asp:GridView>

    Code behind.

     protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
            {
          
                if(e.Row.RowType == DataControlRowType.DataRow)
                {
    // here a dropdown has many listitem , you could add listitem according to the column count of your excel
    // and webfrom will rebuild the dropdownlist again when posting back
    // one dropdownlist represents one row of your excel DropDownList list = e.Row.FindControl("DropDownList1") as DropDownList; list.Items.Add(new ListItem("A")); list.Items.Add(new ListItem("B")); list.Items.Add(new ListItem("C")); } } protected void Button1_Click(object sender, EventArgs e) { foreach (GridViewRow item in GridView1.Rows) { if (item.RowType == DataControlRowType.DataRow) {
    // get the values in dropdownlist DropDownList list = item.FindControl("DropDownList1") as DropDownList; foreach (ListItem option in list.Items) { Response.Write(option.Value); } Response.Write("<br/>"); } } }

    The result.

    Best regards,

    Ackerly Xu

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Thursday, March 14, 2019 7:40 AM

All replies

  • User-893317190 posted

    Hi callykalpana,

    It seems you dynamically create your hidden field in the gridview's rowdatabound event.

    This will cause a problem , because webfom will not recreate dynamically created controls when your page posts back so you will lose your controls and find controls in the cell is zero.

    In addition , because  usually databind is finished in  !ispostback, so your rowdatabound event will not fire  when the page posts back , you could debug to have a check.

    This will cause  your control to disappear even in html when the page posts back you could open F12 to have a check.

    One solution is that you could get the value from Request.Form, because although webform will not recreate dynamically created controls , the value of these controls will be stored in Request.Form. 

    Below is a sample.

     <form id="form1" runat="server">
            <asp:GridView ID="GridView1" runat="server" OnRowDataBound="GridView1_RowDataBound">
               
            </asp:GridView>
         
            <asp:Button ID="Button1" runat="server" Text="Button"  OnClick="Button1_Click"/>
        </form>
     public partial class GridViewSqlAdapter : System.Web.UI.Page
        {
            private static string constr = ConfigurationManager.ConnectionStrings["EntityDb"].ConnectionString;
            protected void Page_Load(object sender, EventArgs e)
            {
               
                if (!IsPostBack)
                {
    
                   
                    using (SqlDataAdapter adapter = new SqlDataAdapter("select * from MasterInfo_Log  ", constr))
                    {
                        adapter.SelectCommand.Parameters.Add(new SqlParameter(namf,value))
    
                    
    
                        DataTable table = new DataTable();
                       
                        adapter.Fill(table);
    
                        GridView1.DataSource = table; 
                        GridView1.DataBind();
                    }
    
    
                }
                if (IsPostBack)
                {               // loop through the Form.Keys
                    foreach (var item in Request.Form.Keys)
                    {
                        Response.Write(item.ToString()+":"+Request.Form[item.ToString()]);
                        Response.Write("<br/>");
                    }
                 
                }
            }
    
            protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
            {
                if(e.Row.RowType == DataControlRowType.DataRow)
                {
                    TextBox box = new TextBox();
                    box.ID = "target"; // set an id
                    e.Row.Cells[1].Controls.Add(box);
                }
            }
    
            protected void Button1_Click(object sender, EventArgs e)
            {
             
            }
        }

    The result.

    You could see the format is GridViewId$ctlrownumber$controllId , you could use  String.EndWith and String.Split to check whether it is what you want.

    But in this way , you should recreate hidden field every time the page posts back(because rowdatabound will not file when page posts back) or the controls will disappear even in html after post back.

    Another way is to put hidden field in aspx and just dynamically set its value  in rowdatabound , in this way , you could find the controls in gridview.

    For example,

     <asp:GridView ID="GridView1" runat="server" OnRowDataBound="GridView1_RowDataBound">
                <Columns>
                    <asp:TemplateField>
                        <ItemTemplate>
                            <asp:HiddenField ID="HiddenField1" runat="server" />
                            <asp:HiddenField ID="HiddenField2" runat="server" />
                        </ItemTemplate>
                    </asp:TemplateField>
                </Columns>
            </asp:GridView>

    Best regards,

    Ackerly Xu

    Tuesday, March 12, 2019 8:24 AM
  • User2015884762 posted

    HI Ackerly

    Thank you for replying. The second option looks easier, however, only 3 out of 10 columns in the GridView are specified in the aspx page, the other 7 are created dynamically in the code behind, and it is for this 7 columns that the rows and the hidden fields are created on the fly. Once the gridview is populated, then user will use the button click to submit the generated data to db. I was thinking of using data table as a parameter to be sent to the db using stored procedure.

    What other alternatives do you suggest on sending the data generated in the gridview to the database. ?

    Tuesday, March 12, 2019 9:26 AM
  • User-893317190 posted

    Hi 

    I don't understand why you want to  create column at code behind.How about write column at aspx?

    If you don't want to show the hidden field's column , you could write as follows.

     <Columns>
                    <asp:TemplateField>
                        <ItemTemplate>
                            <asp:HiddenField ID="HiddenField1" runat="server" />
                            
                        </ItemTemplate>
                        
                    </asp:TemplateField>
                    <asp:TemplateField   HeaderStyle-CssClass="hide">
                        <ItemStyle  CssClass="hide" />
                        <ItemTemplate>
                            <asp:HiddenField ID="HiddenField2" runat="server" Value="abc" />
                        </ItemTemplate>
                    </asp:TemplateField>
                </Columns>

    The the hide class.

     <style>
            .hide{
                display:none
            }
        </style>

    Another way,if you only want to make use of the hidden fields ,  you could add all the hidden field in the three columns in aspx and  you could  use different id to identity them.

    I think you don't need  so many  dynamically created controls since dynamically created controls are hard to maintain.

    Best regards,

    Ackerly Xu

    Tuesday, March 12, 2019 9:49 AM
  • User2015884762 posted

    HI Ackerly,

    The reason for the columns at the code behind is because I am actually importing data from Excel, it depends on the sheet, at times, the excel can have different number of columns. Hence the reason.

    Thursday, March 14, 2019 7:15 AM
  • User-893317190 posted

    Hi targetData_fullday,

    If so , I suggest you could add a control that could store mutiple values , such as dropdownlist , gridview and so on.

    Here  I make a small sample with dropdown list.

     <form id="form1" runat="server">
            <asp:GridView ID="GridView1" DataKeyNames="InfoId" runat="server" OnRowDataBound="GridView1_RowDataBound" AutoGenerateSelectButton="true" OnSelectedIndexChanged="GridView1_SelectedIndexChanged">
                <Columns>
                    <asp:TemplateField>
                        <ItemTemplate>
                            <asp:DropDownList ID="DropDownList1" runat="server" Visible="false"></asp:DropDownList>
                            
                        </ItemTemplate>
                        
                    </asp:TemplateField>
                  
                </Columns>
            </asp:GridView>

    Code behind.

     protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
            {
          
                if(e.Row.RowType == DataControlRowType.DataRow)
                {
    // here a dropdown has many listitem , you could add listitem according to the column count of your excel
    // and webfrom will rebuild the dropdownlist again when posting back
    // one dropdownlist represents one row of your excel DropDownList list = e.Row.FindControl("DropDownList1") as DropDownList; list.Items.Add(new ListItem("A")); list.Items.Add(new ListItem("B")); list.Items.Add(new ListItem("C")); } } protected void Button1_Click(object sender, EventArgs e) { foreach (GridViewRow item in GridView1.Rows) { if (item.RowType == DataControlRowType.DataRow) {
    // get the values in dropdownlist DropDownList list = item.FindControl("DropDownList1") as DropDownList; foreach (ListItem option in list.Items) { Response.Write(option.Value); } Response.Write("<br/>"); } } }

    The result.

    Best regards,

    Ackerly Xu

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Thursday, March 14, 2019 7:40 AM
  • User2015884762 posted

    Hi Ackerly

    Thank you for your explanation, I did some study and I found out that dynamically created columns are not really encouraged, furthermore when I have 7 of it with 15 rows of gridview, that's whole of data to retrieve during postback. I have decided to include the columns on the page and now the values are retained during postback. Thank you.

    Tuesday, March 26, 2019 6:30 AM
  • User-893317190 posted

    Hi callykalpana,

    Yes , dynamic created control  will not be maintained by webform  as well as the data in it.

    You should maintain the control and its data all by yourself which is not a good way to make use of webform.

    It will be easy to program without dynamic control.

    Best regards,

    Ackerly Xu

    Tuesday, March 26, 2019 6:36 AM