Hi ifblipika,
Check this example. Now please take its reference and correct your code.
HTML
<table border="0" cellpadding="0" cellspacing="0">
<tr>
<td>
Name: <asp:TextBox runat="server" ID="txtName" />
</td>
</tr>
<tr>
<td>
Country: <asp:TextBox runat="server" ID="txtCountry" />
</td>
</tr>
</table>
<br />
<asp:Button Text="Add" OnClick="Add" runat="server" />
<br />
<br />
<asp:GridView runat="server" ID="gvCustomers" />
Namespaces
C#
using System.Data;
VB.Net
Imports System.Data
Code
C#
protected void Add(object sender, EventArgs e)
{
DataTable dt = new DataTable();
dt.Columns.AddRange(new DataColumn[3] { new DataColumn("Id", typeof(int)),
new DataColumn("Name", typeof(string)),
new DataColumn("Country",typeof(string)) });
dt.Rows.Add(1, "John Hammond", "United States");
dt.Rows.Add(2, "Mudassar Khan", "India");
dt.Rows.Add(3, "Suzanne Mathews", "France");
dt.Rows.Add(4, "Robert Schidner", "Russia");
string name = txtName.Text;
string country = txtCountry.Text;
if (!string.IsNullOrEmpty(name) && !string.IsNullOrEmpty(country))
{
DataRow[] rows = dt.Select("Name='" + name + "' AND Country='" + country + "'");
if (rows.Length == 0)
{
dt.Rows.Add(dt.Rows.Count + 1, name, country);
}
}
gvCustomers.DataSource = dt;
gvCustomers.DataBind();
}
VB.Net
Protected Sub Add(ByVal sender As Object, ByVal e As EventArgs)
Dim dt As DataTable = New DataTable()
dt.Columns.AddRange(New DataColumn(2) {New DataColumn("Id", GetType(Integer)),
New DataColumn("Name", GetType(String)),
New DataColumn("Country", GetType(String))})
dt.Rows.Add(1, "John Hammond", "United States")
dt.Rows.Add(2, "Mudassar Khan", "India")
dt.Rows.Add(3, "Suzanne Mathews", "France")
dt.Rows.Add(4, "Robert Schidner", "Russia")
Dim name As String = txtName.Text
Dim country As String = txtCountry.Text
If Not String.IsNullOrEmpty(name) AndAlso Not String.IsNullOrEmpty(country) Then
Dim rows As DataRow() = dt.Select("Name='" & name & "' AND Country='" & country & "'")
If rows.Length = 0 Then
dt.Rows.Add(dt.Rows.Count + 1, name, country)
End If
End If
gvCustomers.DataSource = dt
gvCustomers.DataBind()
End Sub
Screenshot
