Click here to Skip to main content
15,902,032 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have a datagrid having 3 columns userid,city and description.Uisng sql connection get the data and display the output,woriking fine.but i have to add edit and delete button for a particular cell .can you please help me how to do it???

and my sql database table is like this:-

ColumnName DataType
UserId Int(set identity property=true)
UserName varchar(50)
City varchar(50)
Designation varchar(50)

What I have tried:

my .cs code is:-

C#
SqlConnection con = new SqlConnection("Data Source=MITSCPU108;Initial Catalog=sss;User ID=sa;Password=mits123$");
 protected void Page_Load(object sender, EventArgs e)
 {
     if (!IsPostBack)
     {
         BindEmployeeDetails();
     }
 }
 protected void BindEmployeeDetails()
 {
     con.Open();
     SqlCommand cmd = new SqlCommand("Select * from Employee_Details", con);
     SqlDataAdapter da = new SqlDataAdapter(cmd);
     DataSet ds = new DataSet();
     da.Fill(ds);
     con.Close();
     if (ds.Tables[0].Rows.Count > 0)
     {
         gvDetails.DataSource = ds;
         gvDetails.DataBind();
     }
     else
     {
         ds.Tables[0].Rows.Add(ds.Tables[0].NewRow());
         gvDetails.DataSource = ds;
         gvDetails.DataBind();
         int columncount = gvDetails.Rows[0].Cells.Count;
         gvDetails.Rows[0].Cells.Clear();
         gvDetails.Rows[0].Cells.Add(new TableCell());
         gvDetails.Rows[0].Cells[0].ColumnSpan = columncount;
         gvDetails.Rows[0].Cells[0].Text = "No Records Found";
     }
 }
 protected void gvDetails_RowEditing(object sender, GridViewEditEventArgs e)
 {
     gvDetails.EditIndex = e.NewEditIndex;
     BindEmployeeDetails();
 }
 protected void gvDetails_RowUpdating(object sender, GridViewUpdateEventArgs e)
 {
     int userid = Convert.ToInt32(gvDetails.DataKeys[e.RowIndex].Value.ToString());
     string username = gvDetails.DataKeys[e.RowIndex].Values["UserName"].ToString();
     TextBox txtcity = (TextBox)gvDetails.Rows[e.RowIndex].FindControl("txtcity");
     TextBox txtDesignation = (TextBox)gvDetails.Rows[e.RowIndex].FindControl("txtDesg");
     con.Open();
     SqlCommand cmd = new SqlCommand("update Employee_Details set City='" + txtcity.Text + "',Designation='" + txtDesignation.Text + "' where UserId=" + userid, con);
     cmd.ExecuteNonQuery();
     con.Close();
     lblresult.ForeColor = Color.Green;
     lblresult.Text = username + " Details Updated successfully";
     gvDetails.EditIndex = -1;
     BindEmployeeDetails();
 }
 protected void gvDetails_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
 {
     gvDetails.EditIndex = -1;
     BindEmployeeDetails();
 }
 protected void gvDetails_RowDeleting(object sender, GridViewDeleteEventArgs e)
 {
     int userid = Convert.ToInt32(gvDetails.DataKeys[e.RowIndex].Values["UserId"].ToString());
     string username = gvDetails.DataKeys[e.RowIndex].Values["UserName"].ToString();
     con.Open();
     SqlCommand cmd = new SqlCommand("delete from Employee_Details where UserId=" + userid, con);
     int result = cmd.ExecuteNonQuery();
     con.Close();
     if (result == 1)
     {
         BindEmployeeDetails();
         lblresult.ForeColor = Color.Red;
         lblresult.Text = username + " details deleted successfully";
     }
 }
 protected void gvDetails_RowCommand(object sender, GridViewCommandEventArgs e)
 {
     if (e.CommandName.Equals("AddNew"))
     {
         TextBox txtUsrname = (TextBox)gvDetails.FooterRow.FindControl("txtftrusrname");
         TextBox txtCity = (TextBox)gvDetails.FooterRow.FindControl("txtftrcity");
         TextBox txtDesgnation = (TextBox)gvDetails.FooterRow.FindControl("txtftrDesignation");
         con.Open();
         SqlCommand cmd =
         new SqlCommand(
         "insert into Employee_Details(UserName,City,Designation) values('" + txtUsrname.Text + "','" +
         txtCity.Text + "','" + txtDesgnation.Text + "')", con);
         int result = cmd.ExecuteNonQuery();
         con.Close();
         if (result == 1)
         {
             BindEmployeeDetails();
             lblresult.ForeColor = Color.Green;
             lblresult.Text = txtUsrname.Text + " Details inserted successfully";
         }
         else
         {
             lblresult.ForeColor = Color.Red;
             lblresult.Text = txtUsrname.Text + " Details not inserted";
         }
     }
 }


my aspx code is:-

HTML
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>Untitled Page</title>
<style type="text/css">
.Gridview
{
font-family:Verdana;
font-size:10pt;
font-weight:normal;
color:black;
}
</style>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:GridView ID="gvDetails" DataKeyNames="UserId,UserName" runat="server"
AutoGenerateColumns="false" CssClass="Gridview" HeaderStyle-BackColor="#61A6F8"
ShowFooter="true" HeaderStyle-Font-Bold="true" HeaderStyle-ForeColor="White"
onrowcancelingedit="gvDetails_RowCancelingEdit"
onrowdeleting="gvDetails_RowDeleting" onrowediting="gvDetails_RowEditing"
onrowupdating="gvDetails_RowUpdating"
onrowcommand="gvDetails_RowCommand">
<Columns>
    <asp:TemplateField>
        <EditItemTemplate>
            <asp:ImageButton ID="imgbtnUpdate" CommandName="Update" runat="server" value="update" ImageUrl="~/Images/update.jpg" ToolTip="Update" Height="20px" Width="20px" />
            <asp:ImageButton ID="imgbtnCancel" runat="server" CommandName="Cancel" value="Cancel"  ImageUrl="~/Images/Cancel.jpg" ToolTip="Cancel" Height="20px" Width="20px" />
        </EditItemTemplate>
        <ItemTemplate>
            <asp:ImageButton ID="imgbtnEdit" CommandName="Edit" runat="server" ImageUrl="~/Images/Edit.jpg" ToolTip="Edit" Height="20px" Width="20px" />
            <asp:ImageButton ID="imgbtnDelete" CommandName="Delete" Text="Edit" runat="server" ImageUrl="~/Images/delete.jpg" ToolTip="Delete" Height="20px" Width="20px" />
        </ItemTemplate>
        <FooterTemplate>
            <asp:ImageButton ID="imgbtnAdd" runat="server" ImageUrl="~/Images/AddNewitem.jpg" CommandName="AddNew" Width="30px" Height="30px" ToolTip="Add new User" ValidationGroup="validaiton" />
        </FooterTemplate>
    </asp:TemplateField>
    <asp:TemplateField HeaderText="UserName">
        <EditItemTemplate>
           <asp:Label ID="lbleditusr" runat="server" Text='<%#Eval("Username") %>'/>
        </EditItemTemplate>
        <ItemTemplate>
          <asp:Label ID="lblitemUsr" runat="server" Text='<%#Eval("UserName") %>'/>
        </ItemTemplate>
        <FooterTemplate>
            <asp:TextBox ID="txtftrusrname" runat="server"/>
            <asp:RequiredFieldValidator ID="rfvusername" runat="server" ControlToValidate="txtftrusrname" Text="*" ValidationGroup="validaiton"/>
        </FooterTemplate>
    </asp:TemplateField>
    <asp:TemplateField HeaderText="City">
        <EditItemTemplate>
           <asp:TextBox ID="txtcity" runat="server" Text='<%#Eval("City") %>'/>
        </EditItemTemplate>
        <ItemTemplate>
          <asp:Label ID="lblcity" runat="server" Text='<%#Eval("City") %>'/>
        </ItemTemplate>
        <FooterTemplate>
            <asp:TextBox ID="txtftrcity" runat="server"/>
            <asp:RequiredFieldValidator ID="rfvcity" runat="server" ControlToValidate="txtftrcity" Text="*" ValidationGroup="validaiton"/>
        </FooterTemplate>
    </asp:TemplateField>
    <asp:TemplateField HeaderText="Designation">
        <EditItemTemplate>
          <asp:TextBox ID="txtDesg" runat="server" Text='<%#Eval("Designation") %>'/>
        </EditItemTemplate>
        <ItemTemplate>
          <asp:Label ID="lblDesg" runat="server" Text='<%#Eval("Designation") %>'/>
        </ItemTemplate>
        <FooterTemplate>
           <asp:TextBox ID="txtftrDesignation" runat="server"/>
           <asp:RequiredFieldValidator ID="rfvdesignation" runat="server" ControlToValidate="txtftrDesignation" Text="*" ValidationGroup="validaiton"/>
        </FooterTemplate>
    </asp:TemplateField>
</Columns>
</asp:GridView>
</div>
<div>
 <asp:Label ID="lblresult" runat="server"></asp:Label>
</div>
</form>
</body>
</html>
Posted
Updated 20-Nov-16 21:34pm
v2
Comments
Where is the problem?
NagaNimesh 11474558 19-Nov-16 6:16am    
here im adding the buttons in a column by the wat each row having that button but i want to add a button to a particular cell in a grid not to all the rows. can u plz help me??

Currently your gridview is


ASP.NET
<asp:GridView ID="gvDetails" DataKeyNames="UserId,UserName" runat="server"
AutoGenerateColumns="false" CssClass="Gridview" HeaderStyle-BackColor="#61A6F8"
ShowFooter="true" HeaderStyle-Font-Bold="true" HeaderStyle-ForeColor="White"
onrowcancelingedit="gvDetails_RowCancelingEdit"
onrowdeleting="gvDetails_RowDeleting" onrowediting="gvDetails_RowEditing"
onrowupdating="gvDetails_RowUpdating"
onrowcommand="gvDetails_RowCommand">


Now add in end rowdatabound event

ASP.NET
 <asp:GridView ID="gvDetails" DataKeyNames="UserId,UserName" runat="server"
AutoGenerateColumns="false" CssClass="Gridview" HeaderStyle-BackColor="#61A6F8"
ShowFooter="true" HeaderStyle-Font-Bold="true" HeaderStyle-ForeColor="White"
onrowcancelingedit="gvDetails_RowCancelingEdit"
onrowdeleting="gvDetails_RowDeleting" onrowediting="gvDetails_RowEditing"
onrowupdating="gvDetails_RowUpdating"
onrowcommand="gvDetails_RowCommand" 
OnRowDataBound="gvDetails_RowDataBound"
>



Then in codebehind add new method for this event as

C#
protected void gvDetails_RowDataBound(object sender, GridViewRowEventArgs e)
{
    if(e.Row.RowType==DataControlRowType.DataRow)  
        { 
               /// here you can put ur criteria to either delete those buttons which are generating for each row except for .....
        } 
}


this method is calling for each row automatically and it is more powerful then Databound in that u've to use foreach
 
Share this answer
 
Comments
NagaNimesh 11474558 22-Nov-16 0:18am    
tanq so much.i got the output.
Mohtshm Zubair 22-Nov-16 4:41am    
Plz mark it solved!
First off, don't hard code your connection string in your code behind file. You should put the config in your web.config file under connectionString element.

Second, make it a habit to put objects that eat resources such as SqlConnection, SqlCommand and SqlDataAdapter within a using Statement[^] to ensure that objects will be properly disposed and closed after they are used.

Third, do not use DataSet when you are only dealing with 1 result set. Instead you could use a DataTable.

Now back to your original question. Since you already have setup the Edit and Delete buttons within your GridView, then you can use the RowDataBound event to hide the buttons based on your requirement. For example:

C#
protected void gvDetails_RowDataBound(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        ImageButton imgEdit = (ImageButton)e.Row.FindControl("imgbtnEdit");
        ImageButton imgDelete = (ImageButton)e.Row.FindControl("imgbtnDelete");
        if("<your condition="" here="" to="" hide="" your="" buttons="">"){
                      imgEdit.Visible = false;
                      imgDelete.Visible = false;
        }
    }
}
 
Share this answer
 
v2
Comments
F-ES Sitecore 21-Nov-16 4:18am    
"using" and explicit disposal is only needed for objects that use resources that are not under the control of .net such as SqlConnection which uses a database connection. SqlCommand etc do not need any special disposing as they don't use resources not controlled by .net.
Vincent Maverick Durano 21-Nov-16 4:31am    
I always prefer to put SqlCommand and any object that implements IDisposable within the "using statement" to dispose them and to free up memory. Adding to that, it makes the code more readable it saves me from having to write the cleanup code.
F-ES Sitecore 21-Nov-16 4:46am    
Well good news, you don't have to :) Disposing an object doesn't free up memory, it is the garbage collection that does that. As I said in my comment, you only have to worry about explicit disposing when non .net resources are being held by the component as you'll want those resources released immediately and not left to the garbage collector. That's why it is common to see using around SqlConnection, or anything to do with file access, sockets, streams and so on as those components all hold non .net resources, it's nothing to do with freeing up memory.
Vincent Maverick Durano 21-Nov-16 5:08am    
Point taken :) but yet, I still prefer wrapping my SqlCommands within the "using" block :)
NagaNimesh 11474558 22-Nov-16 0:17am    
tanq so much all for your suggestion.finally I got the output.
u can've full control on it by databound event of gridview, which is fired after binding of data . Then delete or remove those buttons from all the rows except the desire one on the basis of particular record. Plz check those events.
Infact What I suggest add those buttons in that row databound event will be much better and cleaner.


C#
protected void GridView_DataBound(object sender, EventArgs e)
    { 
 
Share this answer
 
Comments
NagaNimesh 11474558 21-Nov-16 0:33am    
thankx for the rly but im sry,still i didnt able to get the output will u plz give me some code related to that??
NagaNimesh 11474558 22-Nov-16 0:18am    
tanq so much Mr.Mohtshm Zubair

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