Click here to Skip to main content
15,901,284 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
C#
 public void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        
        SqlConnection con = new SqlConnection(str);
         try
            {
            if (e.CommandName == "update")
            {                
                LinkButton linbtnupdate = (LinkButton)e.CommandSource;
                int index = Convert.ToInt32(linbtnupdate.CommandArgument);
           this.ID =((HiddenField)GridView1.Rows[index].FindControl("HiddenField1")).Value;

//The problem lies here..!!i am not able to use "this.id" below in public void bttn_Update_Click(object sender, EventArgs e) event

                DataSet ds = new DataSet();              
                con.Open();
                string sqlquery = "select Name, Gender, Address, State, city, Zipcode,Username from  Registration_Simple where id=" + this.ID;
                getDataset(sqlquery, ds);
                string Name = ds.Tables[0].Rows[0]["Name"].ToString();
                string Gender = ds.Tables[0].Rows[0]["Gender"].ToString();
                string Address = ds.Tables[0].Rows[0]["Address"].ToString();
                string State = ds.Tables[0].Rows[0]["State"].ToString();
                string city = ds.Tables[0].Rows[0]["city"].ToString();
                string Zipcode = ds.Tables[0].Rows[0]["Zipcode"].ToString();
                string Username = ds.Tables[0].Rows[0]["Username"].ToString();
                TxtName.Text = Name;
                Txt_Gender.Text = Gender;
                txtAddress.Text = Address;
                TxtState.Text = State;
                Txtcity.Text = city;
                TxtZipcode.Text = Zipcode;
                Txt_Username.Text = Username;
            }

         }
            catch (Exception ex)
            {
                throw ex;
         
            }
            finally
            {
                con.Close();
            }
    }

public void bttn_Update_Click(object sender, EventArgs e)
    {
        SqlConnection con = new SqlConnection(str);
        SqlDataAdapter da = new SqlDataAdapter();
        SqlCommand cmd = new SqlCommand();
          try
            {
                con.Open();
                cmd.CommandType = CommandType.StoredProcedure;
                cmd.CommandText = "sp_Update_Registration_Simple";
                cmd.Parameters.AddWithValue("@id", this.ID);//*****How to use this.id in here?
                cmd.Parameters.AddWithValue("@Name", TxtName.Text);
                cmd.Parameters.AddWithValue("@Gender", Txt_Gender.Text);
                cmd.Parameters.AddWithValue("@Address", txtAddress.Text);
                cmd.Parameters.AddWithValue("@State", TxtState.Text);
                cmd.Parameters.AddWithValue("@City", Txtcity.Text);
                cmd.Parameters.AddWithValue("@Zipcode", TxtZipcode.Text);
                cmd.Parameters.AddWithValue("@USERNAME", Txt_Username.Text);
                cmd.ExecuteNonQuery();       
          }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                con.Close();
            }
          Response.Write("DATA UPDATED");
        }       


//ASPX Code

ASP.NET
<%@ Page Language="C#" AutoEventWireup="true"  CodeFile="Grid_View_RegisteredUsers.aspx.cs" Inherits="_Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server" style="background-image: url('Penguins.jpg')">
    <div>
        <asp:GridView ID="GridView1" runat="server" 
            AutoGenerateColumns="False"  CellPadding="4" 
            EnableModelValidation="True" ForeColor="#333333" HorizontalAlign="Center" 
            Height="164px" onrowcommand="GridView1_RowCommand" 
            onrowupdating="GridView1_RowUpdating" >
            <AlternatingRowStyle BackColor="White" />
        <Columns>
         <asp:TemplateField>
            <ItemTemplate>
                <asp:HiddenField ID="HiddenField1" runat="server" Visible="true" Value='<%#Bind("id")%>'/>
            </ItemTemplate>            
            
            </asp:TemplateField>
        <asp:TemplateField HeaderText="Name">
        <ItemTemplate>
        <asp:Label ID="lblName" runat="server" Text='<%#Bind("Name") %>'></asp:Label>
        </ItemTemplate>
        </asp:TemplateField>
         <asp:TemplateField HeaderText="Gender">
        <ItemTemplate>
        <asp:Label ID="lblGender" runat="server" Text='<%#bind("Gender") %>'>'></asp:Label>
        </ItemTemplate>
        </asp:TemplateField>
        <asp:TemplateField HeaderText="Address">
        <ItemTemplate>
        <asp:Label ID="lblAddress" runat="server" Text='<%#Bind("Address") %>'></asp:Label>
        </ItemTemplate>
        </asp:TemplateField>
        <asp:TemplateField HeaderText="State">
        <ItemTemplate>
        <asp:Label ID="lblState" runat="server" Text='<%#bind("State") %>'></asp:Label>
        </ItemTemplate>
        </asp:TemplateField>
        <asp:TemplateField HeaderText="City">
        <ItemTemplate>
        <asp:Label ID="lblCity" runat="server" Text='<%#bind("City") %>'>'></asp:Label>
        </ItemTemplate>
        </asp:TemplateField>
        <asp:TemplateField HeaderText="Zipcode">
        <ItemTemplate>
        <asp:Label ID="lblZipcode" runat="server" Text='<%#bind("Zipcode") %>'>'></asp:Label>
        </ItemTemplate>
        </asp:TemplateField>
         <asp:TemplateField HeaderText="USERNAME">
        <ItemTemplate>
        <asp:Label ID="lblUSERNAME" runat="server" Text='<%#bind("UserName") %>'>'></asp:Label>
        </ItemTemplate>
        </asp:TemplateField>
        <asp:TemplateField>
            <ItemTemplate>
                <asp:LinkButton ID="btnUpdate" runat="server" Text="Edit" CommandArgument="<%#((GridViewRow)Container).RowIndex %>" CommandName="update"></asp:LinkButton>
            </ItemTemplate>
            </asp:TemplateField>
        </Columns>
        <EditRowStyle BackColor="#2461BF" />
            <FooterStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
            <HeaderStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
            <PagerStyle BackColor="#2461BF" ForeColor="White" HorizontalAlign="Center" />
            <RowStyle BackColor="#EFF3FB" />
            <SelectedRowStyle BackColor="#D1DDF1" Font-Bold="True" ForeColor="#333333" />

        </asp:GridView>
    </div>
    <div style="height: 50px; width: 595px;">    
         </div>
    <div>
      <table>

    <tr>
    <td>
    Name:  
    </td>
    <td>
    <asp:TextBox ID="TxtName" runat="server" Width="200" onfocus="if(this.value=='Enter your Name please')this.value='';"></asp:TextBox>
    </td>
    </tr>
    <tr>
    <td>
    <asp:Label ID="Lbl_Gender" runat="server" Text="Gender"></asp:Label>
    </td>
    <td>
    <asp:TextBox ID="Txt_Gender" runat="server" Width="198px"></asp:TextBox>
     </td>
    </tr>
    <tr>
    <td>
    Address:
    </td>
    <td>
   <asp:TextBox ID="txtAddress" runat="server" Width="200" onfocus="if(this.value='Enter Address')this,value=''"></asp:TextBox>
    </td>
    </tr>
    <tr>
    <td>
    State:
    </td>
    <td>
    <asp:textbox ID="TxtState" runat="server" Width="200" onfocus="if(this.value='Enter your State Name Please')this.value=''"></asp:textbox>
    </td>
    </tr>
    <tr>
    <td>
    City:
    </td>
    <td>
    <asp:TextBox ID="Txtcity" runat="server" Width="200" onfocus="if(this.value=='Enter your City Name Please')this.value=''"></asp:TextBox>
    </td>
    </tr>
    <tr>
    <td>
    Zipcode:
    </td>
    <td>
    <asp:TextBox ID="TxtZipcode" runat="server" Width="200" onfocus="if(this.value=='Enter Your Zip Code Please')this.value=''"></asp:TextBox>
    </td>
    </tr>
    <tr>
    <td>
    <asp:Label ID ="lblUsername" runat="server" Text="USERNAME"></asp:Label>
    </td>
    <td>
    <asp:TextBox ID="Txt_Username" runat="server"></asp:TextBox>
    </td>
    </tr>
    <tr align="justify">
    <td>
    <asp:Button ID="bttn_Register" runat="server" Text="REGISTER" 
            onclick="bttn_Register_Click" />
    </td>
    <td align="center">
    <asp:Button ID="bttn_Update" runat="server" Text="UPDATE" 
            onclick="bttn_Update_Click"/>
    </td>
    <td>
    <asp:Button ID="Bttn_CLEAR" runat="server" Text="CLEAR" BorderStyle="Double" 
            onclick="Bttn_CLEAR_Click" />
    </td>
    </tr>
    </table>
    </div>
    </form>
</body>
</html>
Posted
Updated 4-Oct-13 19:30pm
v3
Comments
Richard MacCutchan 4-Oct-13 9:05am    
Your question is not clear. What is the value of the ID variable, and why can you not use it?
Itz_ashish_Singh 4-Oct-13 9:14am    
ID carries the Row_ID from the grid view when i click on linkbutton present in grid view....what i did is extracted data table form database onto grid view then i used a link button(EDIT) to transfer data from grid view to textboxes..Now i want to update this data using Update button..
CodeBlack 4-Oct-13 9:32am    
can you show me your ASPX code ?

In Your .aspx file Grid Source...

C#
<itemtemplate>
<asp:linkbutton id="linkbtnEdit" runat="server" commandname="EditRecord" commandargument="<%#Eval("YourID") %>" xmlns:asp="#unknown">Edit</asp:linkbutton>
</itemtemplate>


And handle it from your OnRowCommand()...

C#
protected void MyGridView_RowCommand(object sender, GridViewCommandEventArgs e)
{
   int YourID = Convert.ToInt32(e.CommandArgument.ToString());
   //Here Your Edit Logic goes
}


Hope This Help
------------------
Pratik Bhuva
 
Share this answer
 
Comments
Itz_ashish_Singh 5-Oct-13 3:20am    
hii,
i am able to retrieve ID in MyGridView_RowCommand(object sender, GridViewCommandEventArgs e) event but

but i want to use ID in "bttn_Update_Click" event to update my data..

basically wat im doing is by using "linkbutton" provided in Gridview i am able to transfer data of the selected row on to Text boxes.Not i want to Edit a particulat text box value and update it using Update button..
Pratik Bhuva 5-Oct-13 3:39am    
here you can try...
protected void MyGridView_RowCommand(object sender, GridViewCommandEventArgs e)
{
int YourID = Convert.ToInt32(e.CommandArgument.ToString());
Response.Redirect("~/Editpage.aspx?pid=" + Yourid);
}

and on your edit page you can retrive yourID from query string.
then do sql operation for select * from TBL where id == YourID
Now bind all data to textboxes and then update.

OR You can Try is...
Get ID from Query String And then assign it into class level static variable.
like...
class myClass
{
static int ClassMember_ID = 0;

YourUpdateEvent()
{
//here you can use it.
}
}
Pratik Bhuva 5-Oct-13 3:41am    
use class level static variable it might work in your scenario.
Itz_ashish_Singh 7-Oct-13 2:30am    
hey..

i used ViewState to retrieve ID..

Thnx for ur help :)
hello profession

problam i here:-

<asp:LinkButton ID="btnUpdate" runat="server" Text="Edit" CommandArgument="<%#((GridViewRow)Container).RowIndex %>" CommandName="update"></asp:LinkButton>


you need to bind the ID field of your table on here
JavaScript
<asp:LinkButton ID="btnUpdate" runat="server" Text="Edit" CommandArgument='<%#Bind("id")%>' CommandName="update"></asp:LinkButton>


or CommandArgument='<%#Eval("id") %>'

just think for updation you need a where condition in your update query

and for it u need like this...
on event

C#
public void GridView1_RowCommand(object sender,GridViewCommandEventArgs e)
{
Int32 ID= Convert.ToInt32(e.CommandArgument);
now u got you excat ID that you want in ID field
// and do the update task 
}
<pre></pre>


Happy to help!!!
 
Share this answer
 
v3
Comments
Itz_ashish_Singh 5-Oct-13 2:51am    
i have already binded ID field using hidden field

<asp:TemplateField>
<itemtemplate>
<asp:HiddenField ID="HiddenField1" runat="server" Visible="true" Value='<%#Bind("id")%>'/>


plz have a luk at the aspx.xs code howe i retived the ID using

if (e.CommandName == "update")
{
LinkButton linbtnupdate = (LinkButton)e.CommandSource;
int index = Convert.ToInt32(linbtnupdate.CommandArgument);
this.ID =((HiddenField)GridView1.Rows[index].FindControl("HiddenField1")).Value;

i am able to retrieve the row index in "GridView1_RowCommand" event but im unbale to retrieve row index in Bttn_UPDATE_clicl event!!
Shubh Agrahari 5-Oct-13 4:08am    
why u r binding like this....
<asp:LinkButton ID="btnUpdate" runat="server" Text="Edit" CommandArgument="<%#((GridViewRow)Container).RowIndex %>" CommandName="update">

bind ur ID filed like this
<asp:LinkButton ID="btnUpdate" runat="server" Text="Edit" CommandArgument='<%#Eval("ID") %>' CommandName="update">

and after it just do like this

if (e.CommandName == "update")
{
LinkButton linbtnupdate = (LinkButton)e.CommandSource;
int ID= Convert.ToInt32(e.CommandArgument);

//now check with break point is int ID holding value of row ar not...
}
Itz_ashish_Singh 8-Oct-13 4:52am    
problem was solved with the help of view state ...

thnx.. :)
Shubh Agrahari 8-Oct-13 5:08am    
hmm ya you can also use view state or Session...okk good but always maintain view state security after Use
you must use value of this .id to it or pass value to this.id
 
Share this answer
 
C#
public partial class _Default : System.Web.UI.Page 
{
    string str = System.Configuration.ConfigurationManager.ConnectionStrings["_constr"].ConnectionString;
    protected void Page_Load(object sender, EventArgs e)
    {        
        SqlConnection con = new SqlConnection(str);  
        SqlCommand cmd = new SqlCommand("select * from Registration_Simple",con);
        SqlDataAdapter da = new SqlDataAdapter(cmd);
        DataSet ds = new DataSet();
        da.Fill(ds);
        GridView1.DataSource = ds.Tables[0];
        GridView1.DataBind();    
    }
    public void getDataset(string sql, DataSet ds)
    {
        SqlConnection con = new SqlConnection(str);
        SqlDataAdapter da = new SqlDataAdapter();
        con.Open();
        da = new SqlDataAdapter(sql, con);
        da.Fill(ds);
        con.Close();
    }
    public void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        SqlConnection con = new SqlConnection(str);
         try
            {
            if (e.CommandName == "update")
            {                
                LinkButton linbtnupdate = (LinkButton)e.CommandSource;
                int index = Convert.ToInt32(linbtnupdate.CommandArgument);
 
//changes made:-->starts from here  
             
String ID1 = ((HiddenField)GridView1.Rows[index].FindControl("HiddenField1")).Value;
                int a = int.Parse(ID1);
                ViewState["HiddenID"] = a;
 
//changes made till here !!
                DataSet ds = new DataSet();              
                con.Open();
                string sqlquery = "select Name, Gender, Address, State, city, Zipcode,Username from  Registration_Simple where id=" + ID1;
                getDataset(sqlquery,ds);     
                string Name = ds.Tables[0].Rows[0]["Name"].ToString();
                string Gender = ds.Tables[0].Rows[0]["Gender"].ToString();
                string Address = ds.Tables[0].Rows[0]["Address"].ToString();
                string State = ds.Tables[0].Rows[0]["State"].ToString();
                string city = ds.Tables[0].Rows[0]["city"].ToString();
                string Zipcode = ds.Tables[0].Rows[0]["Zipcode"].ToString();
                string Username = ds.Tables[0].Rows[0]["Username"].ToString();
                TxtName.Text = Name;
                Txt_Gender.Text = Gender;
                txtAddress.Text = Address;
                TxtState.Text = State;
                Txtcity.Text = city;
                TxtZipcode.Text = Zipcode;
                Txt_Username.Text = Username;
            }
         }
            catch (Exception ex)
            {
                throw ex;        
            }
            finally
            {
                con.Close();
            }
    }
    protected void Bttn_CLEAR_Click(object sender, EventArgs e)
    {
        TxtName.Text = null;
        Txt_Gender.Text = null;
        txtAddress.Text = null;
        TxtState.Text = null;
        Txtcity.Text = null;
        TxtZipcode.Text = null;
        Txt_Username.Text = null;
    }
    protected void bttn_Register_Click(object sender, EventArgs e)
    {
        Response.Redirect("Registration.aspx");
    }
    public void bttn_Update_Click(object sender, EventArgs e)
    {
        SqlConnection con = new SqlConnection(str);
        SqlCommand cmd = new SqlCommand("sp_Update_Registration_Simple", con);
        try
        {            
            con.Open();
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.CommandText = "sp_Update_Registration_Simple";
            cmd.Parameters.AddWithValue("@id", ViewState["HiddenID"]);
            cmd.Parameters.AddWithValue("@Name", TxtName.Text);
            cmd.Parameters.AddWithValue("@Gender", Txt_Gender.Text);
            cmd.Parameters.AddWithValue("@Address", txtAddress.Text);
            cmd.Parameters.AddWithValue("@State", TxtState.Text);
            cmd.Parameters.AddWithValue("@City", Txtcity.Text);
            cmd.Parameters.AddWithValue("@Zipcode", TxtZipcode.Text);
            cmd.Parameters.AddWithValue("@USERNAME", Txt_Username.Text);
            cmd.ExecuteNonQuery();
            Response.Write("DATA UPDATED");
        }
        catch (Exception ex)
        {
            throw ex;
        }
        finally
        {
            con.Close();
        }
    }
 
Share this answer
 
Hi ,
you can get the Id by this way..
C#
public void bttn_Update_Click(object sender, EventArgs e)
    {
 using (GridViewRow gvrow = (GridViewRow)((LinkButton)sender).Parent.Parent)
            {
               string id = (gvrow.Cells[0].Text); 
               // if id is the first cell  of the gridview
            }
     }


thanks
Animesh
 
Share this answer
 
Comments
Itz_ashish_Singh 4-Oct-13 9:54am    
Hiits shows error..

Unable to cast object of type 'System.Web.UI.WebControls.Button' to type 'System.Web.UI.WebControls.LinkButton'.
Animesh Datta 4-Oct-13 10:06am    
This will not work as i think your update_button is inside the gridview. If it is inside the gridview then just change the line
using (GridViewRow gvrow = (GridViewRow)((LinkButton)sender).Parent.Parent) to
using (GridViewRow gvrow = (GridViewRow)((Button)sender).Parent.Parent) .as the sender is a button instead of LinkButton but to complete your requirement you can take one hiddenfiled and set the hidden field value in row command and use that value in update_button_click method.
thanks
Animesh
Itz_ashish_Singh 4-Oct-13 23:48pm    
heyy animesh,
My Update button isn't in the Grid view.As u can see above,i have link buttons in grid view.These link buttons are use to transfer data columns to the text boxes and i have used UPDATE button in the new division along with text boxes..All i need is to to extract the ID of the selected row from the grid view and use this ID in Update button click event to update my data...
Thanks :)
Animesh Datta 5-Oct-13 1:16am    
hello ,
i know that the update button is not in your gridview. that's why i recommend you to use one hidden filed in your project . and assign that id(which you want) value in the hidden field in row command event . and then the use that value whenever it needs .
Itz_ashish_Singh 5-Oct-13 1:20am    
Exactly animesh...
I am already using hiddenfield "ID"..
but i am not able to use this hiddenfield "ID" in Update_bttn click event...How to do that?
thnks..

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900