locked
get values from gridview to textboxes (outside gridview) for updating when i click on editlink button RRS feed

  • Question

  • User-1324830691 posted

    i have itemid , itemname ,location.. columns in my database ..

    i dont want to show itemid ...so i used autogeneratecolumns="false" datakeys="itemid" and a command argument as itemid...but when i click on edit button i am getting id correctly but the values of next columns are loaded into my textbox because the gridview considers my itemid as index values and loads next colum data to textboxes..i do i get correct data to textboxes ..i am hanling it with onrowcommand event..even i used commandname="Edit its not loading" as it considers it as index value...i am looking it for a week ...still i could not resolve it

    Tuesday, January 17, 2017 8:04 PM

Answers

  • User-1034726716 posted

    If you are not editing data within the GridView then just use a TemplateField column and add a LinkButton/Button there.  Then you can do something like this to get the row values when clicking the button:

    protected void lnkEdit_Click(object sender, EventArgs e)
    {
            LinkButton lb = (LinkButton)sender;
            GridViewRow row = (GridViewRow)lb.NamingContainer;
            if (row != null)
            {
                //gets the row index selected
                int index = row.RowIndex; 
                
                //gets the datakey
                string itemID = GridView1.DataKeys(index).Value.ToString();
    
                //access row values and assign it to your TextBox
                TextBox1.Text = row.Cells[0].Text;
                TextBox2.Text = row.Cells[1].Text;
    
                //If you are using TemplateField then you can access them using FindControl() method
    
                TextBox3.Text = ((TextBox)row.FindControl("YourTextBoxIDFromGridViewRow")).Text;
            }
    }

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Wednesday, January 18, 2017 12:45 AM

All replies

  • User-1034726716 posted

    If you are not editing data within the GridView then just use a TemplateField column and add a LinkButton/Button there.  Then you can do something like this to get the row values when clicking the button:

    protected void lnkEdit_Click(object sender, EventArgs e)
    {
            LinkButton lb = (LinkButton)sender;
            GridViewRow row = (GridViewRow)lb.NamingContainer;
            if (row != null)
            {
                //gets the row index selected
                int index = row.RowIndex; 
                
                //gets the datakey
                string itemID = GridView1.DataKeys(index).Value.ToString();
    
                //access row values and assign it to your TextBox
                TextBox1.Text = row.Cells[0].Text;
                TextBox2.Text = row.Cells[1].Text;
    
                //If you are using TemplateField then you can access them using FindControl() method
    
                TextBox3.Text = ((TextBox)row.FindControl("YourTextBoxIDFromGridViewRow")).Text;
            }
    }

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Wednesday, January 18, 2017 12:45 AM
  • User-707554951 posted

    Hi mohammednadeem474,

    Just from your description. I am not sure what you want to.

    Would you please provide us with related code you have down.

    So that we could find you problem and give you a solution as soon as possible.

    Best Regards

    Cathy

    Wednesday, January 18, 2017 7:25 AM
  • User-1716253493 posted

    If you dont want to show itemid, you can use DataKeyNames = "itemid"

    Then bind itemindex instead

    CommandArgument='<%# Container.DataItemIndex %>'

    Based commandargument value (item index), you can get DataKey and another values

    Wednesday, January 18, 2017 8:57 AM
  • User-1324830691 posted

    my source view------------(its a content page inheriting master) and a update panel---------------

    <asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceBodylist"  runat="Server">
         <asp:Button ID="TestSave" runat="server" BackColor="BlueViolet" ForeColor="White" Text="TestSave" OnClick="TestSave_Click" />
                        
        <asp:UpdatePanel ID="ItemMasterUP" UpdateMode="Conditional" runat="server" ChildrenAsTriggers="true">
                        <ContentTemplate>

         <div style="margin-top:-30px; border:solid 1px #c3c3c3; height:600px;">
           
             
                <div class="title_div" >
                <asp:Label ID = "LblitemsTag" runat="server" Text ="Master items" ForeColor="Green" Font-Bold="true"></asp:Label>
                
                    </div>
                    <div class="form_set">
                        <%--left end--%>
            <div style="float:left; width:50%;padding:10px 0;">
            <div class="ste_pro_row1">
                <div class="ste_pro_row1_txt">
                  <asp:Label ID="lblItemName" runat="server" Text="Item Name">Item Name<span style="color:Red;">*</span> </asp:Label> :
                </div>
                <div class="ste_pro_row1_txt_box">  
                    <asp:TextBox ID="txtItemName" runat="server"
                        class ="text_div_bg_textHeight" Height="25px" Width="144px"></asp:TextBox>
                         
                    

                           
                </div>
                </div>
                 
                 
                
                 
                     <div class="ste_pro_row1">
                 <div class="ste_pro_row1_txt">
                    <asp:Label ID="lblCost" runat="server" Text="Cost">Cost<span style="color:Red;">*</span> </asp:Label> :
                    </div>
             <div class="ste_pro_row1_txt_box">
                     <div class="ste_pro_row1_txt_box" style="margin-left:0px;">
                     <asp:TextBox ID="txtCost" runat="server" onkeypress="return validatenumerics(event);"
                        class ="text_div_bg_textHeight" Height="25px" Width="144px"></asp:TextBox>
                </div>
                    

                           
                </div>
                </div>
               <div class="ste_pro_row1" >
                    <div class="ste_pro_row1_txt">
                    <asp:Label ID="lblLocation" runat="server" Text="Location">Location<span style="color:Red;"></span> </asp:Label> :
                </div>
                <div class="ste_pro_row1_txt_box" >
                
                    <asp:TextBox ID="txtlocation" runat="server" class ="text_div_bg_textHeight" Height="25px" Width="144px"></asp:TextBox>
                     <%--  <asp:RequiredFieldValidator ID="RFElocationtxt" runat="server" ErrorMessage="Please enter Location" Width="200px"
                                ControlToValidate="txtlocation" Display="None"  SetFocusOnError="true" ValidationGroup="Popup"></asp:RequiredFieldValidator>
                         <asp:ValidatorCalloutExtender ID="VCElocationtxt" runat="server"
                               CssClass="CustomValidatorCalloutStyle" TargetControlID="RFElocationtxt"  
                               WarningIconImageUrl="../GenericImages/warning_red.png"></asp:ValidatorCalloutExtender>--%>
                   
                </div>
                </div>  
                
                    
              <div class="ste_pro_row1">
                 <div class="ste_pro_row1_txt">
                    <asp:Label ID="lblDescription" runat="server" Text="Description"> Description<span style="color:Red;"></span> </asp:Label> :
                    </div>
             <div class="ste_pro_row1_txt_box">
             <asp:TextBox ID="txtDesc" runat="server"  
                        class ="text_div_bg_textHeight" Height="25px" Width="144px"
                        TextMode="MultiLine"  ></asp:TextBox>
                         <%-- <asp:RequiredFieldValidator ID="RFVtxtDesc" runat="server" ErrorMessage="Please enter Description" Width="200px"
                                ControlToValidate="txtDesc" Display="None"  SetFocusOnError="true" ValidationGroup="Popup"></asp:RequiredFieldValidator>
                         <asp:ValidatorCalloutExtender ID="VCEtxtDesc" runat="server"
                               CssClass="CustomValidatorCalloutStyle" TargetControlID="RFVtxtDesc"  
                               WarningIconImageUrl="../GenericImages/warning_red.png"></asp:ValidatorCalloutExtender>--%>
                     
                </div>
                </div>
                <div class="ste_pro_row1">
                 <div class="ste_pro_row1_txt">
                     
                    </div>
             <div class="ste_pro_row1_txt_box">
                   
                    
                    

                           
                </div>
                </div>   
               
                
                   <div class="ste_pro_row1" style=" float:left;">
          <div style="float:right;">
                          <asp:Button ID="DeleteButton" runat="server"  Text="Delete" CausesValidation="false"  style="background-color: Transparent;
                        background-image: url(../GenericImages/cancel.png)" ForeColor="#ffffff"   OnClientClick="return Confirmation('Delete')"  
                                                     CssClass="bg_button_new" BorderStyle="None" Font-Bold="True"
                         ValidationGroup="Popup" OnClick="DeleteButton_Click1"/>  
          </div>

         
          
           
               <div style="float:right;">
                          <asp:Button ID="SaveButton" OnClick="SaveButton_Click" runat="server"  Text="Save"  style="background-color: Transparent;
                         background-image: url(../GenericImages/save_btn.png)" ForeColor="#ffffff"
                                                     CssClass="bg_button_new" BorderStyle="None" Font-Bold="True" CausesValidation="true" ValidationGroup="Popup"  />  
                       <%--<asp:Button ID="UpdateButton" runat="server"  Text="Update" CausesValidation="false"  style="background-color: Transparent;
                         background-image: url(../GenericImages/save_btn.png)" ForeColor="#ffffff"
                                                     CssClass="bg_button_new" BorderStyle="None" Font-Bold="True"
                         ValidationGroup="Popup"  OnClientClick="return Confirmation('Update')"  />  --%>
          </div>
             <div style="float:right;">
                          <asp:Button ID="NewButton" runat="server"  Text="New"  style="background-color: Transparent;
                         background-image: url(../GenericImages/ubdate_btn.png)" ForeColor="#ffffff"
                                                     CssClass="bg_button_new" BorderStyle="None" Font-Bold="True"
                         ValidationGroup="Popup"  CausesValidation="false" OnClientClick="return Confirmation('New')" OnClick="NewButton_Click1" />  
          </div>

          </div>   
               
                    <div class="ste_pro_row1">
                 <div class="ste_pro_row1_txt">
                   
                    </div>
             <div class="ste_pro_row1_txt_box">
                         
                </div>
                </div>
                 
            </div>

            <%--right--%>        <%--right end--%>
            <div style="float:left; width:50%;padding:10px 0;">
            
                     <div class="ste_pro_row1">
                    <div class="ste_pro_row1_txt">
                    <asp:Label ID="lblDateofexpire" runat="server" Text="Date of expire"></asp:Label> :
                </div>
                <div class="ste_pro_row1_txt_box">
                     <asp:TextBox ID="txtDateofexpire" ReadOnly="false" runat="server" SkinID="SmallTextbox" class ="text_div_bg_textHeight" Height="25px" Width="144px"></asp:TextBox>
                  <%-- <asp:RequiredFieldValidator ID="RFVtxtexpdt" runat="server" ErrorMessage="Please enter Expire Date" Width="200px"
                                ControlToValidate="txtDateofexpire" Display="None"  SetFocusOnError="true" ValidationGroup="Popup"></asp:RequiredFieldValidator>
                         <asp:ValidatorCalloutExtender ID="VCEtxtdt" runat="server"
                               CssClass="CustomValidatorCalloutStyle" TargetControlID="RFVtxtexpdt"  
                               WarningIconImageUrl="../GenericImages/warning_red.png"></asp:ValidatorCalloutExtender>--%>
                           
                </div>
                 <div id="imgtxtDate" class="calendarstyle">
                                   
                                    </div>
                </div>
                 
                    
                 <div class="ste_pro_row1">
                    <div class="ste_pro_row1_txt">
                    <asp:Label ID="lblqnt" runat="server" Text="Quantity">Quantity<span style="color:Red;">*</span> </asp:Label> :
                </div>
                <div class="ste_pro_row1_txt_box">
                   <asp:TextBox ID="txtQuantity" runat="server" class ="text_div_bg_textHeight" onkeypress="return validatenumerics(event);" Height="25px" Width="144px"></asp:TextBox>
                    
                     <asp:RequiredFieldValidator ID="RFVQtytxt" runat="server" ErrorMessage="Please enter Qty" Width="200px"
                                ControlToValidate="txtQuantity" Display="None"  SetFocusOnError="true" ValidationGroup="Popup"></asp:RequiredFieldValidator>
                         </div>
                    <div>  <asp:Label ID="lblQty" runat="server"></asp:Label> </div>
                </div>
                <div class="ste_pro_row1">
                 <div class="ste_pro_row1_txt">
                    <asp:Label ID="UnitsLbl" runat="server" Text="Units">Units<span style="color:Red;">*</span> </asp:Label> :
                    </div>
             <div class="ste_pro_row1_txt_box">
                 <asp:DropDownList ID="UnitTypesDLL" runat="server" Height="25px" Width="144px">
                       <asp:ListItem Value="0">Select</asp:ListItem>
                       <asp:ListItem Value="1">Kilo Grams</asp:ListItem>
                       <asp:ListItem Value="2">Grams</asp:ListItem>
                       <asp:ListItem Value="3">Litre</asp:ListItem>
                       <asp:ListItem Value="4">Metre</asp:ListItem>
                       <asp:ListItem Value="5">Per Piece</asp:ListItem>
                    </asp:DropDownList>
                    <asp:RequiredFieldValidator ID="RFVUnitType" runat="server" ErrorMessage="Please select UnitType" InitialValue="--Select--" ControlToValidate="UnitTypesDLL" Display="None"  SetFocusOnError="true" ValidationGroup="Popup"></asp:RequiredFieldValidator>
               
                    
                   
                    
                           
                </div>
                </div>
                <%--<div class="ste_pro_row1">
                 <div class="ste_pro_row1_txt">
                    <asp:Label ID="SuppFaxLbl" runat="server" Text="Fax"></asp:Label> :
                    </div>
             <div class="ste_pro_row1_txt_box">
                    <asp:TextBox ID="SuppFaxTxt" runat="server" class ="text_div_bg_textHeight" Height="25px" Width="144px"></asp:TextBox>
                   
                           
                </div>
                </div>--%>
                <div class="ste_pro_row1">
                 <div class="ste_pro_row1_txt">'
                    <asp:Label ID="lblUnitPrice" runat="server" Text="Unit Prices">Unit Prices<span style="color:Red;">*</span> </asp:Label> :
                    </div>
             <div class="ste_pro_row1_txt_box">
                    <%--<asp:TextBox ID="SuppmailTxt" runat="server" class ="text_div_bg_textHeight"    onchange="return checkMail();" Height="25px" Width="144px"></asp:TextBox>
                   --%>
                   <asp:TextBox ID="txtUnitPrice" runat="server" class ="text_div_bg_textHeight" onkeypress="return validatenumerics(event);" Height="25px" Width="144px"></asp:TextBox>
                      
                </div>
                <div class="ste_pro_row1">
                 <div class="ste_pro_row1_txt">
                    
                    </div>
             <div class="ste_pro_row1_txt_box">
                   

                           
                </div>
                </div>
               <%--  <div class="ste_pro_row1"></div>--%>
                 
           
              </div>   
            </div>
                            <div style="margin-top:10px; " class="auto-style1">
                            <asp:Panel ID="Panel1" runat="server" DefaultButton = "SearchButton">
                            
    <div style="margin-left:300px;">
     <asp:label ID="lblItemSearch" runat="server" Text="Item Name :" CssClass="Itemsearch_lbl"></asp:label>
    <asp:TextBox ID="SearchItemsTextBox"  runat="server" Width="200px" Height="30px" ClientIDMode="Static" CssClass="text_box" />
        <asp:HiddenField ID="hfCustomerId" runat="server" />
        <asp:TextBox ID="txtItemid" runat="server" />
        <asp:Label ID="lblhf" runat="server"></asp:Label>
     <%-- <asp:AutoCompleteExtender ID="SearchItemsTextBox_AutoCompleteExtender"  runat="server" DelimiterCharacters="" Enabled="True" ServicePath="" MinimumPrefixLength="1"
      TargetControlID="SearchItemsTextBox" EnableCaching="true" CompletionSetCount="1" CompletionInterval="1000" ServiceMethod="GetSupplierNames" >
     </asp:AutoCompleteExtender>--%></div>
            <div>
                <asp:Button runat="server" ID="SearchButton" Text="Find" CausesValidation="True"                 
                                   
                    
                    style="background-color: Transparent; background-image: url(../GenericImages/search_btn.png)"
                    ForeColor="#ffffff" CssClass="bg_button_new" BorderStyle="None"
                            Font-Bold="false"   /> </div>
                            
     

        <div><asp:Button runat="server" ID="ShowAllButton" Text="Show All"  CausesValidation="True" style="background-color: Transparent; background-image: url(../GenericImages/showall_btn.png)" ForeColor="#ffffff"
                                                     CssClass="bg_button_new" BorderStyle="None"
                                     Font-Bold="false" />
                                     
                                    
                                     </div>
                                     
                                     <div>
                                     
                                </div>
                                
           
               
                                   

                                </asp:Panel>
             </div>
                    
                        <div class="form_set2">
                            <br />
                            <br />
                            <br />
                            <div class="scrollcss">
                                <asp:GridView ID="ItemGridView" OnRowCreated="ItemGridView_RowCreated" runat="server" AllowPaging="true" AllowSorting="true" AllowEditing="true" AutoGenerateColumns="False" BackColor="#ffff99" BorderColor="#99ff33" DataKeyNames="ItemId" EmptyDataText="No Rows To Display" ForeColor="Black" GridLines="Both" OnPageIndexChanging="ItemGridView_PageIndexChanging" OnRowCancelingEdit="ItemGridView_RowCancelingEdit" onrowcommand="ItemGridView_RowCommand" OnRowDeleting="ItemGridView_RowDeleting" OnRowEditing="ItemGridView_RowEditing" OnRowUpdating="ItemGridView_RowUpdating" onselectedindexchanged="ItemGridView_SelectedIndexChanged" OnSorting="ItemGridView_Sorting" ShowHeader="true" ShowHeaderWhenEmpty="True" Width="96%">
                                    <Columns>
                                        <asp:TemplateField HeaderStyle-Width="10%" HeaderText="Action">
                                            <ItemTemplate>
                                                <asp:LinkButton ID="EditLinkbtn" runat="server" CommandName="Edit" CommandArgument='<%#Eval("ItemId") %>'> Edit</asp:LinkButton>
                                            </ItemTemplate>
                                        </asp:TemplateField>
                                        <asp:BoundField DataField="ItemName" HeaderText="ItemName" ItemStyle-Width="12%" ReadOnly="true" SortExpression="ItemName" />
                                        <asp:BoundField DataField="Cost" HeaderText="Cost" ItemStyle-Width="20%" SortExpression="Cost" />
                                        <asp:BoundField DataField="Dateofexpire" DataFormatString="{0:MM/dd/yy}" HeaderText="Dateofexpire" ItemStyle-Width="20%" SortExpression="Dateofexpire" />
                                        <asp:BoundField DataField="Quantity" HeaderText="Quantity" ItemStyle-Width="20%" SortExpression="Quantity" />
                                        <asp:BoundField DataField="Units" HeaderText="Units" ItemStyle-Width="20%" SortExpression="Unit" />
                                        <asp:BoundField DataField="UnitPrice" HeaderText="UnitPrice" ItemStyle-Width="20%" SortExpression="UnitPrice" />
                                        <asp:BoundField DataField="Location" HeaderText="Location" ItemStyle-Width="20%" SortExpression="Location" />
                                        <%-- <asp:BoundField   DataField="Address2" HeaderText="Address2" />--%>
                                        <asp:BoundField DataField="Description" HeaderText="Description" />
                                    </Columns>
                                    <AlternatingRowStyle BackColor="#CCCCCC" />
                                    <RowStyle Font-Size="35px" Height="40px" HorizontalAlign="Left" />
                                    <EmptyDataRowStyle BackColor="#ffff99" BorderStyle="Solid" ForeColor="Red" HorizontalAlign="Center" />
                                    <HeaderStyle BackColor="#c0c0c0" Font-Bold="true" ForeColor="#0066ff" HorizontalAlign="Left" />
                                    <PagerStyle BackColor="#999999" ForeColor="Black" HorizontalAlign="Center" />
                                    <FooterStyle BackColor="#CCCCCC" />
                                    <AlternatingRowStyle Font-Size="XX-Large" Height="40px" HorizontalAlign="Center" />
                                    <SortedAscendingCellStyle BackColor="#F1F1F1" />
                                    <SortedAscendingHeaderStyle BackColor="#808080" />
                                    <SortedDescendingCellStyle BackColor="#CAC9C9" />
                                    <SortedDescendingHeaderStyle BackColor="#383838" />
                                </asp:GridView>
                            </div>
                        </div>
                                
    </div>
             </ContentTemplate>
             <Triggers>
            <asp:PostBackTrigger ControlID="SaveButton" />
                 
            </Triggers>
             </asp:UpdatePanel>
    </asp:Content>

    Code view ------------------------------------

    public partial class _Default : System.Web.UI.Page
    {
        SqlConnection cn = null;
        SqlDataAdapter da = null;
        DataSet ds = null;
        int rp = 0;
        string strSqlCommmand = string.Empty;
        SqlCommandBuilder bldr = null;
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                ViewState["SortOn"] = "ItemId";
                ViewState["SortBy"] = "Asc";
                BindEmpData();
                BindGridView();
            }
            cn = new SqlConnection("Data Source=USER;User Id=sa;Password=123456;Database=BillData");
            strSqlCommmand = "Select * from ItemsMaster";
            da = new SqlDataAdapter(strSqlCommmand, cn);
            ds = new DataSet();
            da.Fill(ds, "ItemsMaster");
            bldr = new SqlCommandBuilder(da);
        }
        protected void BindGridView()
        {
            cn = new SqlConnection("Data Source=USER;User Id=sa;Password=123456;Database=BillData");
            strSqlCommmand = "Select * from ItemsMaster Order By " + ViewState["SortOn"].ToString() + " " + ViewState["SortBy"].ToString();
            da = new SqlDataAdapter(strSqlCommmand, cn);
            ds = new DataSet();
            da.Fill(ds, "ItemsMaster");
            ItemGridView.DataSource = ds.Tables[0];
            ItemGridView.DataBind();
        }
        protected void BindEmpData() {
            cn = new SqlConnection("Data Source=USER;User Id=sa;Password=123456;Database=BillData");
            strSqlCommmand = "Select * from ItemsMaster";
            da = new SqlDataAdapter(strSqlCommmand, cn);
            ds = new DataSet();
            da.Fill(ds, "ItemsMaster");
            ViewState["ds"] = ds;
            ViewState["rp"] = 0;

        }

        protected void ItemGridView_RowCommand(object sender, GridViewCommandEventArgs e)
        {

            if (e.CommandName == "Edit")
            {
                int index = Convert.ToInt32(e.CommandArgument);

                SaveButton.Text = "Update";
                //int iStID = Convert.ToInt32(e.CommandArgument.ToString());
                int id = Convert.ToInt32(ItemGridView.DataKeys[index].Values[0]);
                GridViewRow gvRow = ItemGridView.Rows[index];
                txtItemid.Text = index.ToString();
                txtItemName.Text = gvRow.Cells[1].Text;
                txtCost.Text = gvRow.Cells[2].Text;
                txtDateofexpire.Text = gvRow.Cells[3].Text;
                txtQuantity.Text = gvRow.Cells[4].Text;
                UnitTypesDLL.SelectedIndex = UnitTypesDLL.Items.IndexOf(UnitTypesDLL.Items.FindByText(gvRow.Cells[5].Text));
                txtUnitPrice.Text = gvRow.Cells[6].Text;
                txtlocation.Text = gvRow.Cells[7].Text;
                txtDesc.Text = gvRow.Cells[8].Text;
            }
    }

        protected void ItemGridView_SelectedIndexChanged(object sender, EventArgs e)
        {
            SaveButton.Text = "Update";
        }

        protected void ItemGridView_RowEditing(object sender, GridViewEditEventArgs e)
        {
            ItemGridView.EditIndex = e.NewEditIndex;
            BindGridView();
        }

        protected void ItemGridView_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
        {

        }

        protected void ItemGridView_RowUpdating(object sender, GridViewUpdateEventArgs e)
        {

        }

        protected void ItemGridView_RowDeleting(object sender, GridViewDeleteEventArgs e)
        {

        }

        protected void ItemGridView_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            ItemGridView.PageIndex = e.NewPageIndex;
            BindGridView();

        }

        protected void ItemGridView_Sorting(object sender, GridViewSortEventArgs e)
        {
            ViewState["SortOn"] = e.SortExpression;
            if (ViewState["SortBy"].ToString() == "Asc")
                ViewState["SortBy"] = "Desc";
            else
                ViewState["SortBy"] = "Asc";
            BindGridView();

        }

        protected void SaveButton_Click(object sender, EventArgs e)
        {
            
            Button btnName = sender as Button;
            switch (btnName.Text)
            {
                case "Save":
                    DataRow dr = ds.Tables["ItemsMaster"].NewRow();
                    //Assigning values to new row
                    dr["ItemName"] = txtItemName.Text.Trim();
                    dr["Cost"] = txtCost.Text.Trim();
                    dr["Dateofexpire"] = txtDateofexpire.Text.Trim();
                    dr["Quantity"] = txtQuantity.Text.Trim();
                    dr["Units"] = UnitTypesDLL.SelectedItem.Text;
                    dr["UnitPrice"] = txtUnitPrice.Text.Trim();
                    dr["Location"] = txtlocation.Text.Trim();
                    dr["Description"] = txtDesc.Text.Trim();
                    ds.Tables["ItemsMaster"].Rows.Add(dr);
                    int rowaffected = da.Update(ds, "ItemsMaster");
                    if (rowaffected > 0)
                    {
                        txtItemName.Text = txtCost.Text = txtDateofexpire.Text = txtQuantity.Text = txtUnitPrice.Text
                              = txtlocation.Text = txtDesc.Text = string.Empty;
                        UnitTypesDLL.SelectedIndex = 0;
                        BindGridView();
                        lblhf.Text = "Data Saved Sucessfully ";
                    }
                    else
                    {
                        Console.WriteLine("Master Items Insertion Failed");
                    }
                    break;
                case "Update":
                    //ur update Code
                    strSqlCommmand = "Update ItemsMaster Set ItemName=@ItemName,Cost=@Cost,Dateofexpire=@Dateofexpire,Quantity=@Quantity,Units=@Units,UnitPrice=@UnitPrice,Location=@Location,Description=@Description Where ItemId=@ItemId";
                    da.UpdateCommand = new SqlCommand(strSqlCommmand, cn);
                    da.UpdateCommand.Parameters.Add("@ItemName",SqlDbType.VarChar,50,"ItemName");
                    SqlParameter pCost =da.UpdateCommand.Parameters.Add("@Cost",SqlDbType.Money);
                    pCost.SourceColumn = "Cost";
                    SqlParameter pDateofexpire = da.UpdateCommand.Parameters.Add("@Dateofexpire", SqlDbType.Date);
                    pDateofexpire.SourceColumn = "Dateofexpire";
                    SqlParameter pQuantity = da.UpdateCommand.Parameters.Add("@Quantity", SqlDbType.Float);
                    pQuantity.SourceColumn = "Quantity";
                    da.UpdateCommand.Parameters.Add("@Units", SqlDbType.VarChar, 50, "Units");
                    SqlParameter pUnitPrice = da.UpdateCommand.Parameters.Add("@UnitPrice", SqlDbType.Float);
                    pUnitPrice.SourceColumn = "UnitPrice";
                    da.UpdateCommand.Parameters.Add("@Location", SqlDbType.VarChar, 50, "Location");

                    da.UpdateCommand.Parameters.Add("@Description", SqlDbType.VarChar, 50, "Description");
                    SqlParameter pItemId = da.UpdateCommand.Parameters.Add("@ItemId", SqlDbType.Float);
                    pItemId.SourceColumn = "ItemId";
                    pItemId.SourceVersion = DataRowVersion.Original;
                    //edit an existing row
                    DataRow[] dr1 = ds.Tables["ItemsMaster"].Select("ItemId= " + txtItemid.Text);
                    dr1[0]["ItemName"] = txtItemName.Text.Trim();
                    dr1[0]["Cost"] = txtCost.Text.Trim();
                    dr1[0]["Dateofexpire"] = txtDateofexpire.Text.Trim();
                    dr1[0]["Quantity"] = txtQuantity.Text.Trim();
                    dr1[0]["Units"] = UnitTypesDLL.SelectedItem.Value;
                    dr1[0]["UnitPrice"] = txtUnitPrice.Text.Trim();
                    dr1[0]["Location"] = txtlocation.Text.Trim();
                    dr1[0]["Description"] = txtDesc.Text.Trim();

                    int rowaffected1 = da.Update(ds, "ItemsMaster");
                    if (rowaffected1 > 0)
                    {
                        SaveButton.Text = "Save";
                        lblhf.Text = "<b style='color:green'>Update Sucessfully!!!</b>";
                        BindGridView();
                    }
                    else
                    {
                        lblhf.Text = "<b style='color:red'>Updation Failed!!!</b>";

                    }
                    break;
            }
            //Inserting a new Row in Dataset Table
            


        }

        protected void NewButton_Click1(object sender, EventArgs e)
        {
            txtItemName.Text = txtCost.Text = txtDateofexpire.Text = txtQuantity.Text = txtUnitPrice.Text =
         txtlocation.Text = txtDesc.Text = string.Empty;
            UnitTypesDLL.SelectedIndex = 0;

        }

        protected void DeleteButton_Click(object sender, EventArgs e)
        {
            DataRow[] dr = ds.Tables["ItemsMaster"].Select("ItemId = " + txtItemid.Text + "");
            BindGridView();
        }

        protected void TestSave_Click(object sender, EventArgs e)
        {
            lblhf.Text = "Working";
        }

        protected void DeleteButton_Click1(object sender, EventArgs e)
        {
            DataRow[] dr = ds.Tables["ItemsMaster"].Select("ItemId = " + txtItemid.Text + "");
            dr[0].Delete();
            int rowaffected = da.Update(ds, "ItemsMaster");

            if (rowaffected > 0)
            {
                lblhf.Text = "<b style='color:red;'>Items deleted</b>";

                txtItemName.Text = txtCost.Text = txtDateofexpire.Text = txtQuantity.Text = txtUnitPrice.Text =
             txtlocation.Text = txtDesc.Text = string.Empty;
                UnitTypesDLL.SelectedIndex = 0;

                BindGridView();
            }
            else
            {
                lblhf.Text = "deletion  Failed";
            }


        }

        protected void SaveUpdate_Click(object sender, EventArgs e)
        {

        }

        protected void ItemGridView_RowCreated(object sender, GridViewRowEventArgs e)
        {
        }
    }

    Wednesday, January 18, 2017 2:15 PM
  • User-1716253493 posted

    itemid is not row index, bind cmdargument to rowindex

    AFAIK, you need to set gv.EditIndex = idx also to make currentrow editable at last code

    Wednesday, January 18, 2017 2:59 PM
  • User-1324830691 posted

    ya ..the item id is mistaken as index so wrong values are loaded to textboxes but  can you show me how to do it ...once see my row command event..for now if want to show it with item id(in gridview )what to do??

    Wednesday, January 18, 2017 7:11 PM
  • User-1034726716 posted

    Have you tried what I've suggested?

    Wednesday, January 18, 2017 11:39 PM
  • User-1324830691 posted

    i have got it the other way..thanks for your suggestion..

    what i did is sent the command argument to database and populated...

    Tuesday, February 14, 2017 9:32 AM