In this article I will explain how to insert new records to SQL Server database using ASP.Net GridView’s Empty Data Template.
Database
The below screenshot displays the structure of the database table that will store the customer records
HTML Markup
Below is the HTML Markup of the ASP.Net GridView control
<asp:GridView ID="GridView1" runat="server" Width="550px" AutoGenerateColumns="false"
AlternatingRowStyle-BackColor="#C2D69B" HeaderStyle-BackColor="green" ShowFooter="true">
<Columns>
<asp:TemplateField HeaderText="Customer Name">
<ItemTemplate>
<%# Eval("CustomerName") %>
</ItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtCustomerName" runat="server" />
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Company Name">
<ItemTemplate>
<%# Eval("CompanyName") %>
</ItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtCompanyName" runat="server" />
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="City">
<ItemTemplate>
<%# Eval("City") %>
</ItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtCity" runat="server"></asp:TextBox>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
</ItemTemplate>
<FooterTemplate>
<asp:Button ID="btnAdd" runat="server" Text="Add" OnClick="Add" CommandName = "Footer" />
</FooterTemplate>
</asp:TemplateField>
</Columns>
<AlternatingRowStyle BackColor="#C2D69B" />
<EmptyDataTemplate>
<tr style="background-color: Green;">
<th scope="col">
Customer Name
</th>
<th scope="col">
Company Name
</th>
<th scope="col">
City
</th>
<th scope="col">
</th>
</tr>
<tr>
<td>
<asp:TextBox ID="txtCustomerName" runat="server" />
</td>
<td>
<asp:TextBox ID="txtCompanyName" runat="server" />
</td>
<td>
<asp:TextBox ID="txtCity" runat="server" />
</td>
<td>
<asp:Button ID="btnAdd" runat="server" Text="Add" OnClick="Add" CommandName = "EmptyDataTemplate" />
</td>
</tr>
</EmptyDataTemplate>
</asp:GridView>
Above you will notice that the ASP.Net GridView is displaying 3 columns, Customer Name, Company Name and City. I have added textboxes and button to add new records in the <FooterTemplate> and <EmptyDataTemplate>.
Binding the GridView
Below is the code to bind the data from the SQL Server database to the ASP.Net GridView control
C#
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
this.BindData();
}
}
private void BindData()
{
string strConnString = ConfigurationManager.ConnectionStrings["conString"].ConnectionString;
DataTable dt = new DataTable();
using (SqlConnection con = new SqlConnection(strConnString))
{
string strQuery = "SELECT * FROM Customers";
SqlCommand cmd = new SqlCommand(strQuery);
using (SqlDataAdapter sda = new SqlDataAdapter())
{
cmd.Connection = con;
con.Open();
sda.SelectCommand = cmd;
sda.Fill(dt);
GridView1.DataSource = dt;
GridView1.DataBind();
}
}
}
VB.Net
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
If Not IsPostBack Then
Me.BindData()
End If
End Sub
Private Sub BindData()
Dim dt As DataTable = New DataTable
Dim strConnString As String = ConfigurationManager.ConnectionStrings("conString").ConnectionString
Using con As SqlConnection = New SqlConnection(strConnString)
Dim strQuery As String = "SELECT * FROM Customers"
Using cmd As SqlCommand = New SqlCommand(strQuery)
Dim sda As SqlDataAdapter = New SqlDataAdapter
cmd.Connection = con
con.Open()
sda.SelectCommand = cmd
sda.Fill(dt)
GridView1.DataSource = dt
GridView1.DataBind()
End Using
End Using
End Sub
The below screenshot displays GridView when there is no data in the database, you will notice that it is displaying the <EmptyDataTemplate> with three textboxes and a button.
Add new record to database using GridView
Below is the code that gets called when the Add button is clicked. This code snippet fires an insert query in the database and inserts the record in the SQL Server database table
C#
protected void Add(object sender, EventArgs e)
{
Control control = null;
if (GridView1.FooterRow != null)
{
control = GridView1.FooterRow;
}
else
{
control = GridView1.Controls[0].Controls[0];
}
string customerName = (control.FindControl("txtCustomerName") as TextBox).Text;
string companyName = (control.FindControl("txtCompanyName") as TextBox).Text;
string city = (control.FindControl("txtCity") as TextBox).Text;
string strConnString = ConfigurationManager.ConnectionStrings["conString"].ConnectionString;
using (SqlConnection con = new SqlConnection(strConnString))
{
using (SqlCommand cmd = new SqlCommand())
{
cmd.Connection = con;
cmd.CommandType = CommandType.Text;
cmd.CommandText = "INSERT INTO [Customers] VALUES(@CustomerName, @CompanyName, @City)";
cmd.Parameters.AddWithValue("@CustomerName", customerName);
cmd.Parameters.AddWithValue("@CompanyName", companyName);
cmd.Parameters.AddWithValue("@City", city);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
}
Response.Redirect(Request.Url.AbsoluteUri);
}
VB.Net
Protected Sub Add(ByVal sender As Object, ByVal e As EventArgs)
Dim control As Control = Nothing
If (Not (GridView1.FooterRow) Is Nothing) Then
control = GridView1.FooterRow
Else
control = GridView1.Controls(0).Controls(0)
End If
Dim customerName As String = CType(control.FindControl("txtCustomerName"), TextBox).Text
Dim companyName As String = CType(control.FindControl("txtCompanyName"), TextBox).Text
Dim city As String = CType(control.FindControl("txtCity"), TextBox).Text
Dim strConnString As String = ConfigurationManager.ConnectionStrings("conString").ConnectionString
Using con As SqlConnection = New SqlConnection(strConnString)
Using cmd As SqlCommand = New SqlCommand
cmd.Connection = con
cmd.CommandType = CommandType.Text
cmd.CommandText = "INSERT INTO [Customers] VALUES(@CustomerName, @CompanyName, @City)"
cmd.Parameters.AddWithValue("@CustomerName", customerName)
cmd.Parameters.AddWithValue("@CompanyName", companyName)
cmd.Parameters.AddWithValue("@City", city)
con.Open()
cmd.ExecuteNonQuery()
con.Close()
Response.Redirect(Request.Url.AbsoluteUri)
End Using
End Using
End Sub
Above after the record is inserted in the database, the page is redirected to itself so that GridView is loaded with the newly inserted record. The below screenshot displays the GridView with the newly added record and now it is displaying the <FooterTemplate> with three textboxes and add button.
If you are facing little trouble then go through this link
Downloads
You can download the sample source code in VB.Net and C# along with the Database script using the download link provided below
Add Records to ASP.Net GridView using Empty Data Template
Thanks Shibashish Mohanty
nice work
ReplyDeleteThanks.
ReplyDelete