locked
Gridview RRS feed

  • Question

  • User-1499457942 posted

    Hi

      I have below code . When i check value on Edit hdf_No it is correct . When i save record (in UpdateData) then in hdf_No it shows Blank

     protected void gvw_RowCommand(object sender, GridViewCommandEventArgs e)
            {
                if (e.CommandName == "EditRow")
                {
                    GridViewRow row = (GridViewRow)((LinkButton)e.CommandSource).NamingContainer;
                    HiddenField hdf_No = (row.FindControl("hdfNo") as HiddenField);
                    txt_Location.Text = ((Label)row.FindControl("lblLocation")).Text;
                    ClientScript.RegisterStartupScript(this.GetType(), "Pop", "openModal();", true);
                }
            }
    
    
    
            protected void UpdateData(object sender, EventArgs e)
            {
                try
                {
                    using (SqlConnection con = new SqlConnection(CommonFunction.connectionString))
                    {
                        SqlCommand cmd = new SqlCommand("Sp_D", con);
                        cmd.CommandType = CommandType.StoredProcedure;
    
                        cmd.Parameters.AddWithValue("@Action", "U");
                        cmd.Parameters.AddWithValue("@No", hdf_No);
                        SqlParameter returnParameter = cmd.Parameters.Add("Returns", SqlDbType.Bit);
                        returnParameter.Direction = ParameterDirection.ReturnValue;
                        con.Open();
                        cmd.ExecuteNonQuery();
    
                    }
                }
                catch (Exception ex)
                {
                    ClientScript.RegisterStartupScript(this.GetType(), "Popup", "ShowPopup('" + ex.Message + "');", true);
                }
            }

    Thanks

    Monday, August 20, 2018 7:25 AM

Answers

  • User-893317190 posted

    Hi  JagjitSingh,

     It seems that you have hiddenfields in your gridview and you want to  set the value of hiddenfield in your modal to the hiddenfield in your grid view row which is to be edited.

     If this is the case, I find you only get the hiddenfield in your gridview and don’t move its value to the hiddenfield in you modal.

     I have made a sample from your past post. Below is my code.

    <asp:GridView ID="gvwCategories"  runat="server"
                    CssClass="table table-bordered table-striped" AutoGenerateColumns="false" OnRowCommand="gvw_RowCommand"
                    ClientIDMode="Static" BorderWidth="1px"  
                    BorderStyle="None" BorderColor="#DEBA84" HeaderStyle-CssClass="GridHeader" 
                     >
                    <HeaderStyle ForeColor="White" Font-Bold="True" BackColor="#428bca"></HeaderStyle>
                    <Columns>
                        
                        <asp:BoundField DataField="EntryNo" HeaderText="EntryNo" InsertVisible="False" ItemStyle-CssClass="hiddencol" HeaderStyle-CssClass="hiddencol" />
                        <asp:BoundField HeaderText="Code" DataField="Code" />
                        <asp:BoundField HeaderText="Description" DataField="Description" />
       
                        <asp:TemplateField HeaderText="Action">
                            <ItemTemplate>
                                <asp:HiddenField ID="hdfNo" runat="server" Value='<%# Eval("EntryNo") %>' />
                                  <asp:Button id="btnEdit"  ToolTip="Update Record"  
                                    CommandName="EditRow"  runat="server" CssClass="btn btn-default" Text="edit" />
                          
                            </ItemTemplate>
                        </asp:TemplateField>
              
                    </Columns>
                    </asp:GridView>
    

          The modal.

            <div class="modal fade" id="myEditModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
            <div class="modal-dialog modal-sm">
                <div class="modal-content">
                    <div class="modal-header bg-primary">
                        <button type="button" class="close" data-dismiss="modal">×</button>
                        <h4 class="modal-title " id="myModalLabel">Add New </h4>
                    </div>
                    <div class="modal-body">
                        <div class="form-horizontal">
                            <div class="form-group">
                                <asp:Label ID="lblCode" runat="server" CssClass="col-sm-4 control-label" Text="Code"></asp:Label>
                                <div class="col-sm-6">
                                    <asp:TextBox ID="txtCode" CssClass="form-control" runat="server"></asp:TextBox>
                                    <asp:RequiredFieldValidator ID="rfv1" CssClass="text-danger" runat="server" ErrorMessage="This field is Required !" ControlToValidate="txtCode"
                                        ValidationGroup="edit">
                                        
    
                                    </asp:RequiredFieldValidator>
                                </div>
                            </div>
                            <div class="form-group">
                                <asp:Label ID="lblDescription" runat="server" CssClass="col-sm-4 control-label" Text="Description"></asp:Label>
                                <div class="col-sm-8">
                                    <asp:TextBox ID="txtDescription"  CssClass="form-control" runat="server"></asp:TextBox>
                                    <asp:RequiredFieldValidator ID="rfv2" CssClass="text-danger" runat="server" ErrorMessage="This field is Required !" ControlToValidate="txtDescription"
                                        ValidationGroup="edit"></asp:RequiredFieldValidator>
                                </div>
                            </div>
                           
                            
                            <div class="form-group">
                                <div class="col-sm-4"></div>
                                <div class="col-sm-4">
                                    <asp:HiddenField ID="hdf_No" runat="server" />
                                    <asp:Button ID="btnInsert" CssClass="btn btn-primary"  runat="server" class="btn btn-primary" Text=" Save "  ValidationGroup="eidt" OnClick="UpdateData"></asp:Button>
                                </div>
                            </div>
                        </div>
                    </div>        
                </div>
            </div>
        </div>
    
    
            <script>
                function openModal() {
                    $('#myEditModal').modal('show')
                }
            </script>
    

    Code behind.

      private static string constr = ConfigurationManager.ConnectionStrings["EntityExe"].ConnectionString;
            protected void Page_Load(object sender, EventArgs e)
            {
                if (!IsPostBack)
                {
                    BindData();
                }
            }
            private void BindData()
            {
                string sql = "select * from entries";
                using (SqlDataAdapter adapter = new SqlDataAdapter(sql, constr))
                {
    
    
                    DataTable table = new DataTable();
                    adapter.Fill(table);
                    gvwCategories.DataSource = table;
                    gvwCategories.DataBind();
    
    
                }
            }
    
            protected void gvw_RowCommand(object sender, GridViewCommandEventArgs e)
            {
                if (e.CommandName == "EditRow")
                {
                    GridViewRow row = (GridViewRow)((Button)e.CommandSource).NamingContainer;
                    HiddenField hdf = (row.FindControl("hdfNo") as HiddenField);
                    hdf_No.Value = hdf.Value;
    
                    txtCode.Text = row.Cells[1].Text;
                    txtDescription.Text =row.Cells[2].Text ;
                    ClientScript.RegisterStartupScript(this.GetType(), "Pop", "openModal();", true);
                }
            }
    
            protected void UpdateData(object sender, EventArgs e)
            {
                try
                {
                    using (SqlConnection con = new SqlConnection(constr))
                    {
                        string sql = "update entries set code=@code ,description=@description where entryNo=@entryNo";
                        SqlCommand cmd = new SqlCommand(sql, con);
    
                        SqlParameter[] sqlParameters = new SqlParameter[]
                        {
                            new SqlParameter("code",SqlDbType.NVarChar,50){Value=txtCode.Text},
                            new SqlParameter("description",SqlDbType.NVarChar,50){Value=txtDescription.Text},
                            new SqlParameter("entryNo",SqlDbType.Int){Value=Convert.ToInt32(hdf_No.Value)}
                        };
                        cmd.Parameters.AddRange(sqlParameters);
     
                        con.Open();
                        cmd.ExecuteNonQuery();
    
                        BindData();
    
    
    
                    }
                }
                catch (Exception ex)
                {
                    ClientScript.RegisterStartupScript(this.GetType(), "Popup", "ShowPopup('" + ex.Message + "');", true);
                }
            }
    

    The result

    Best regards,

    Ackerly Xu

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Tuesday, August 21, 2018 5:47 AM

All replies

  • User753101303 posted

    Hi,

    It is declared where ? The other hdf_No is local to gvw_RowCommand plus you should access its Text property as hdf_No itself is an hidden input field.

    So I believe that hdf_No is null (rather than "blank") because it is not initialized (thinking it is done in gvw_RowCommand ?).

    Monday, August 20, 2018 7:59 AM
  • User-1499457942 posted

    Hi

      When user clicks on Gridview Edit Button Modal Popup opens . I am trying to pass Hidden value as above in Gridview RowCommand. Now when user clicks on Update

    In Modal Popup i have below line

    <div class="form-group">
    <div class="col-sm-4">
    <asp:HiddenField ID="hdf_No" runat="server" />
    </div>
    </div>

    On Debug it shows like this

    <input type="hidden" name="ctl00$MainContentPlaceHolder$hdf_No" id="MainContentPlaceHolder_hdf_No">

    i need that No value. How i can correct according to my code.

    Thanks

    Monday, August 20, 2018 8:07 AM
  • User753101303 posted

    It seems you would need to add the same line to the UpdateData method :

     HiddenField hdf_No = (row.FindControl("hdfNo") as HiddenField);
    

    And then you'll use hdf_No.Text to get the value. I'm not 100% sure thought about how UpdateData is called.

    Monday, August 20, 2018 8:21 AM
  • User-1499457942 posted

    Hi

      It is called like below

    <div class="form-group">
    <asp:Button ID="btnUpdate" CssClass="btn btn-primary" runat="server" class="btn btn-primary" Text=" Update Record" OnClick="UpdateData" ></asp:Button>
    </div>

    Thanks

    Monday, August 20, 2018 8:34 AM
  • User-1716253493 posted
    cmd.Parameters.AddWithValue("@No", hdf_No.Value);

    Monday, August 20, 2018 8:46 AM
  • User-1499457942 posted

    Hi

      I am trying like this but it is returning Null or ""

    Thanks

    Monday, August 20, 2018 8:56 AM
  • User-893317190 posted

    Hi  JagjitSingh,

     It seems that you have hiddenfields in your gridview and you want to  set the value of hiddenfield in your modal to the hiddenfield in your grid view row which is to be edited.

     If this is the case, I find you only get the hiddenfield in your gridview and don’t move its value to the hiddenfield in you modal.

     I have made a sample from your past post. Below is my code.

    <asp:GridView ID="gvwCategories"  runat="server"
                    CssClass="table table-bordered table-striped" AutoGenerateColumns="false" OnRowCommand="gvw_RowCommand"
                    ClientIDMode="Static" BorderWidth="1px"  
                    BorderStyle="None" BorderColor="#DEBA84" HeaderStyle-CssClass="GridHeader" 
                     >
                    <HeaderStyle ForeColor="White" Font-Bold="True" BackColor="#428bca"></HeaderStyle>
                    <Columns>
                        
                        <asp:BoundField DataField="EntryNo" HeaderText="EntryNo" InsertVisible="False" ItemStyle-CssClass="hiddencol" HeaderStyle-CssClass="hiddencol" />
                        <asp:BoundField HeaderText="Code" DataField="Code" />
                        <asp:BoundField HeaderText="Description" DataField="Description" />
       
                        <asp:TemplateField HeaderText="Action">
                            <ItemTemplate>
                                <asp:HiddenField ID="hdfNo" runat="server" Value='<%# Eval("EntryNo") %>' />
                                  <asp:Button id="btnEdit"  ToolTip="Update Record"  
                                    CommandName="EditRow"  runat="server" CssClass="btn btn-default" Text="edit" />
                          
                            </ItemTemplate>
                        </asp:TemplateField>
              
                    </Columns>
                    </asp:GridView>
    

          The modal.

            <div class="modal fade" id="myEditModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
            <div class="modal-dialog modal-sm">
                <div class="modal-content">
                    <div class="modal-header bg-primary">
                        <button type="button" class="close" data-dismiss="modal">×</button>
                        <h4 class="modal-title " id="myModalLabel">Add New </h4>
                    </div>
                    <div class="modal-body">
                        <div class="form-horizontal">
                            <div class="form-group">
                                <asp:Label ID="lblCode" runat="server" CssClass="col-sm-4 control-label" Text="Code"></asp:Label>
                                <div class="col-sm-6">
                                    <asp:TextBox ID="txtCode" CssClass="form-control" runat="server"></asp:TextBox>
                                    <asp:RequiredFieldValidator ID="rfv1" CssClass="text-danger" runat="server" ErrorMessage="This field is Required !" ControlToValidate="txtCode"
                                        ValidationGroup="edit">
                                        
    
                                    </asp:RequiredFieldValidator>
                                </div>
                            </div>
                            <div class="form-group">
                                <asp:Label ID="lblDescription" runat="server" CssClass="col-sm-4 control-label" Text="Description"></asp:Label>
                                <div class="col-sm-8">
                                    <asp:TextBox ID="txtDescription"  CssClass="form-control" runat="server"></asp:TextBox>
                                    <asp:RequiredFieldValidator ID="rfv2" CssClass="text-danger" runat="server" ErrorMessage="This field is Required !" ControlToValidate="txtDescription"
                                        ValidationGroup="edit"></asp:RequiredFieldValidator>
                                </div>
                            </div>
                           
                            
                            <div class="form-group">
                                <div class="col-sm-4"></div>
                                <div class="col-sm-4">
                                    <asp:HiddenField ID="hdf_No" runat="server" />
                                    <asp:Button ID="btnInsert" CssClass="btn btn-primary"  runat="server" class="btn btn-primary" Text=" Save "  ValidationGroup="eidt" OnClick="UpdateData"></asp:Button>
                                </div>
                            </div>
                        </div>
                    </div>        
                </div>
            </div>
        </div>
    
    
            <script>
                function openModal() {
                    $('#myEditModal').modal('show')
                }
            </script>
    

    Code behind.

      private static string constr = ConfigurationManager.ConnectionStrings["EntityExe"].ConnectionString;
            protected void Page_Load(object sender, EventArgs e)
            {
                if (!IsPostBack)
                {
                    BindData();
                }
            }
            private void BindData()
            {
                string sql = "select * from entries";
                using (SqlDataAdapter adapter = new SqlDataAdapter(sql, constr))
                {
    
    
                    DataTable table = new DataTable();
                    adapter.Fill(table);
                    gvwCategories.DataSource = table;
                    gvwCategories.DataBind();
    
    
                }
            }
    
            protected void gvw_RowCommand(object sender, GridViewCommandEventArgs e)
            {
                if (e.CommandName == "EditRow")
                {
                    GridViewRow row = (GridViewRow)((Button)e.CommandSource).NamingContainer;
                    HiddenField hdf = (row.FindControl("hdfNo") as HiddenField);
                    hdf_No.Value = hdf.Value;
    
                    txtCode.Text = row.Cells[1].Text;
                    txtDescription.Text =row.Cells[2].Text ;
                    ClientScript.RegisterStartupScript(this.GetType(), "Pop", "openModal();", true);
                }
            }
    
            protected void UpdateData(object sender, EventArgs e)
            {
                try
                {
                    using (SqlConnection con = new SqlConnection(constr))
                    {
                        string sql = "update entries set code=@code ,description=@description where entryNo=@entryNo";
                        SqlCommand cmd = new SqlCommand(sql, con);
    
                        SqlParameter[] sqlParameters = new SqlParameter[]
                        {
                            new SqlParameter("code",SqlDbType.NVarChar,50){Value=txtCode.Text},
                            new SqlParameter("description",SqlDbType.NVarChar,50){Value=txtDescription.Text},
                            new SqlParameter("entryNo",SqlDbType.Int){Value=Convert.ToInt32(hdf_No.Value)}
                        };
                        cmd.Parameters.AddRange(sqlParameters);
     
                        con.Open();
                        cmd.ExecuteNonQuery();
    
                        BindData();
    
    
    
                    }
                }
                catch (Exception ex)
                {
                    ClientScript.RegisterStartupScript(this.GetType(), "Popup", "ShowPopup('" + ex.Message + "');", true);
                }
            }
    

    The result

    Best regards,

    Ackerly Xu

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Tuesday, August 21, 2018 5:47 AM