In this Post I am going to explain a simple light weight GridView Edit, Delete, and Update functionality. We are going to apply this functionality on Northwind Database, Employee table.
Following are the screen shots.First of all I am going to explain about creating a Connection String.Connection String has mainly 3 properties.
Initial Catalog — Your Database name (Northwind in this case).
Integrated Security – True
Integrated Security will access the SQL Server with the current windows identity established on the Operating System. For more information about Integrated Security refer this. We usually place the connection string in the Web.config file under “Configuration ==> ConnectionStrings” section.
Here is my connection string.
<add name=“NorthwindConnectionString“ connectionString=“Data Source=*****(SQL Server Name);Initial Catalog=NorthWind;Integrated Security=True;“/>
</connectionStrings>
To learn more about different type of connection strings refer this.
Then, after we are done with your connection string in the Web.config file let’s move on to the C# code.
using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["NorthwindConnectionString"].ConnectionString))
{
conn.Open();
using (SqlCommand comm = new SqlCommand(“select E.EmployeeID,E.FirstName,E.LastName,E.Title,E.Country from Employees E”, conn))
SqlDataAdapter da = new SqlDataAdapter(comm);
DataSet ds = new DataSet();
da.Fill(ds);
GridView1.DataSource = ds;
GridView1.DataBind();
}
}
}
The First Line using statement allows the programmer to specify when objects that use resources should release them. The object provided to the using statement must implement the IDisposable interface. This interface provides the Dispose method, which should release the object’s resources. Refer this for Complete Reference.
In the Code you can see I put AutoGenerateColumns=”false”. That means I have to write column names whatever I want to show to the user. If we put AutoGenerateColumns=”True”, that means u don’t have to write any custom code on your page and user can see each and every column in your dataset or datatable whatever you are binding to your gridview.
How can we hide a column in a GridView and access it in the Code behind ?
Writing a Template Field and making it invisible. In the template field I will Place a label or some controls, So that it’s very easy to access those controls in the code behind by using FindControl method.
What is TemplateField, ItemTemplate, and EditItemTemplate?
ItemTemplate is the content to display for the items in the TemplateField.
Take this simple Snippet.
<ItemTemplate>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox runat=”server” ID=”txtLastName” Text=’<%#Eval(“LastName”) %>‘ />
<asp:RequiredFieldValidator runat=”server” ID=”rfdLastName” ControlToValidate=”txtLastName” ValidationGroup=”var1″ ErrorMessage=”*” />
</EditItemTemplate>
</asp:TemplateField>
In the above Snippet you are seeing a label in Item Template that means whenever we are showing GridView to the user Label will be visible to the user. If he clicks edit (or) in the edit mode he can be able to see the Textbox.
The above piece of code will also do the same as label in ItemTemplate and Textbox in the EditItemTemplate. By default all the boundfields will be trasferred as Textboxes in Edit Mode. To avoid this we need to keep the property ReadOnly as false, Then in the edit mode nothing will happenes. It just visible like a label.
<asp:GridView ID=”GridView1″ runat=”server” GridLines=”None” AutoGenerateColumns=”false” AlternatingRowStyle-BackColor=”#EEEEEE” EditRowStyle-BorderColor=”Red” onrowcancelingedit=”GridView1_RowCancelling” onrowcommand=”GridView1_RowCommand” onrowdeleting=”GridView1_RowDeleting” onrowediting=”GridView1_RowEditing” onrowupdating=”GridView1_RowUpdating” DataKeyNames=”EmployeeID”>
<Columns>
<asp:TemplateField Visible=”false” HeaderText=”EmployeeID”> <ItemTemplate>
<asp:Label runat=”server” ID=”EmployeeID” Text=’<%#Eval(“EmployeeID”)%>‘ />
</ItemTemplate>
</asp:TemplateField>
<%–<asp:BoundField HeaderText=”FirstName” DataField=”FirstName” />–%>
<ItemTemplate>
<asp:Label runat=”server” ID=”LastName” Text=’<%#Eval(“LastName”) %>‘ />
</ItemTemplate>
<EditItemTemplate>
<asp:RequiredFieldValidator runat=”server” ID=”rfdLastName” ControlToValidate=”txtLastName” ValidationGroup=”var1″ ErrorMessage=”*” />
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText=”Title”>
<asp:Label runat=”server” ID=”Title” Text=’<%#Eval(“Title”) %>‘ />
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox runat=”server” ID=”txtTitle” Text=’<%#Eval(“Title”) %>‘ />
<asp:RequiredFieldValidator runat=”server” ID=”rfdTitle” ControlToValidate=”txtTitle” ValidationGroup=”var1″ ErrorMessage=”*” /> </EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText=”Country”>
<ItemTemplate>
<asp:Label runat=”server” ID=”Country” Text=’<%#Eval(“Country”) %>‘ />
</ItemTemplate><EditItemTemplate>
<asp:TextBox runat=”server” ID=”txtCountry” Text=’<%#Eval(“Country”) %>‘ />
<asp:RequiredFieldValidator runat=”server” ID=”rfdCountry” ControlToValidate=”txtCountry” ValidationGroup=”var1″ ErrorMessage=”*” />
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText=”Action”>
<ItemTemplate>
<asp:LinkButton ID=”btnEdit” Text=”Edit” runat=”server” CommandName=”Edit” /> <br />
<asp:LinkButton ID=”btnDelete” Text=”Delete” runat=”server” CommandName=”Delete” />
</ItemTemplate>
<EditItemTemplate>
<asp:LinkButton ID=”btnUpdate” Text=”Update” runat=”server” CommandName=”Update” />
<asp:LinkButton ID=”btnCancel” Text=”Cancel” runat=”server” CommandName=”Cancel” />
</EditItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
If you see the Last TemplateField part in the above code, I am using the link buttons for edit, update, delete and cancel. May be you may think why am I using link buttons as we are provided with some command field buttons by GridView.
2) Secondly if you want to include a custom field (some button or link) in the same column it’s not possible.
Ok let’s move on to Code behind what we have to do when user clicks Edit, Delete, Update and Cancel
protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
{
GridView1.EditIndex = e.NewEditIndex;
BindGridData();
}
In the above code snippet as you see GridViewEditEventArgs will give the row number whatever you are editing by NewEditIndex property. So GridView will put the appropriate row into the Edit Mode by assigning row number to its EditIndex property. Then again we have to call that BindGridData () method to bind data for the textboxes.
So once after done with editing data, if we click update the following method will be triggered. It will call OnRowUpdating Event.
1) The First line is to get the Primary Key of the table using DataKeyNames Property of GridView.
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
string s = GridView1.DataKeys[e.RowIndex].Value.ToString();
Label EmployeeID = GridView1.Rows[e.RowIndex].FindControl(“EmployeeID”) as Label; TextBox LastName = GridView1.Rows[e.RowIndex].FindControl(“txtLastName”) as TextBox; TextBox Title = GridView1.Rows[e.RowIndex].FindControl(“txtTitle”) as TextBox;
TextBox Country = GridView1.Rows[e.RowIndex].FindControl(“txtCountry”) as TextBox; String UpdateQuery = string.Format(“UPDATE Employees SET LastName=’{0}’, Title=’{1}’,Country=’{2}’ WHERE EmployeeID = {3}”,LastName.Text, Title.Text,Country.Text, Convert.ToInt32(EmployeeID.Text));
GridView1.EditIndex = -1;
BindGridData(UpdateQuery);
}
private void BindGridData(string Query)
{
string connectionstring = ConfigurationManager.ConnectionStrings["NorthwindConnectionString"].ConnectionString;
using (SqlConnection conn = new SqlConnection(connectionstring)){
conn.Open();
using (SqlCommand comm = new SqlCommand(Query + “;select E.EmployeeID,E.FirstName,E.LastName,E.Title,E.Country from Employees E”, conn))
{
SqlDataAdapter da = new SqlDataAdapter(comm);
DataSet ds = new DataSet();
da.Fill(ds);
GridView1.DataSource = ds;
GridView1.DataBind();
}
}
}
If the user click cancels the following event (OnRowCancelling) will be fired. When you are setting the value of the EditIndex to -1 that means you are exiting from the editmode. So i.e. when user clicks cancel, here we are exiting from the editmode and rebinding the data to the GridView by calling BindGridData method.
protected void GridView1_RowCancelling(object sender, GridViewCancelEditEventArgs e)
{
GridView1.EditIndex = -1;
BindGridData();
}
If the user clicks the Delete button OnRowDeleting event will be fired. The following is the code for that event. Going into that code we are trying to get the primary key of the employee table(EmployeeID) by using GridView DataKeyNames and then pass the Query to the BindGridData method to bind the updated data to the GridView.
{
string EmployeeID = GridView1.DataKeys[e.RowIndex].Value.ToString();
string Query = “delete Employee where Employee.EmployeeID = “ + EmployeeID;
BindGridData(Query);
}
Happy Coding .
No comments:
Post a Comment