Compare Database column with string array using C# and VB.Net in ASP.Net

Last Reply 26 days ago By dharmendr

Posted 26 days ago

Hi All,

I am trying to compare a column in a Table in excel with an array of strings. So, if the cells in column which do not match, the corresponding rows would be deleted.

Below is an example:

My table is:

Name Age Title

Aa       31     Consultant

Bb       32     Consultant

Cc       33     Sr Consultant

Dd       34     Manager

 

My array is

[Aa, Bb, Cc]

Upon comparison the output is:

Name Age Title

Aa       31     Consultant

Bb       32     Consultant

Cc       33     Sr Consultant

Any suggestions please

Regards,

Vikas

Posted 26 days ago Modified on 26 days ago

Hi Vikash21,

Check this example. Now please take its reference and correct your code.

C#

string[] myArray = new string[] { "Aa", "Bb", "Cc" };
System.Data.DataTable dt = new System.Data.DataTable();
dt.Columns.AddRange(new System.Data.DataColumn[] { 
                    new System.Data.DataColumn("Name", typeof(string)),
                    new System.Data.DataColumn("Age", typeof(int)),
                    new System.Data.DataColumn("Title",typeof(string)) });
dt.Rows.Add("Aa", 31, "Consultant");
dt.Rows.Add("Bb", 32, "Consultant");
dt.Rows.Add("Cc", 33, "Sr Consultant");
dt.Rows.Add("Dd", 34, "Manager");

System.Data.DataTable dtFinal = dt.Clone();
for (int i = 0; i < dt.Rows.Count; i++)
{
    if (myArray.Contains(dt.Rows[i]["Name"].ToString()))
    {
        dtFinal.ImportRow(dt.Rows[i]);
    }
}

GridView gvDetails = new GridView();
gvDetails.DataSource = dtFinal;
gvDetails.DataBind();
form1.Controls.Add(gvDetails);

VB.Net

Dim myArray As String() = New String() {"Aa", "Bb", "Cc"}
Dim dt As Data.DataTable = New Data.DataTable()
dt.Columns.AddRange(New Data.DataColumn() {
                    New Data.DataColumn("Name", GetType(String)),
                    New Data.DataColumn("Age", GetType(Integer)),
                    New Data.DataColumn("Title", GetType(String))})
dt.Rows.Add("Aa", 31, "Consultant")
dt.Rows.Add("Bb", 32, "Consultant")
dt.Rows.Add("Cc", 33, "Sr Consultant")
dt.Rows.Add("Dd", 34, "Manager")
Dim dtFinal As Data.DataTable = dt.Clone()
For i As Integer = 0 To dt.Rows.Count - 1
    If myArray.Contains(dt.Rows(i)("Name").ToString()) Then
        dtFinal.ImportRow(dt.Rows(i))
    End If
Next
Dim gvDetails As GridView = New GridView()
gvDetails.DataSource = dtFinal
gvDetails.DataBind()
form1.Controls.Add(gvDetails)

Output

NameAgeTitle
Aa 31 Consultant
Bb 32 Consultant
Cc 33 Sr Consultant