Alfonsus Dhani Alfonsus Dhani - 5 days ago 6
C# Question

Show Multiple Data to Datagridview using C#

I want to show multiple data based on value I input to textboxes. I have data such as :

WSID CasA CasB
1234 200 100
5678 300 200
0987 400 300
6543 500 400


If I input in CasA textbox = 200 and CasB textbox = 200, WSID 1234 and 5678 will be shown. I got some problem, if I input value like above, it just show WSID of CasB. Can anyone help me ?

string lokasinectar = LokasiNectar.Text;
string koneksinectar = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + lokasinectar + ";Extended Properties='Excel 12.0 xml;HDR=YES;IMEX=1';";

int thresholdcasa;
Int32.TryParse(CasA.Text, out thresholdcasa);

int thresholdcasb;
Int32.TryParse(CasB.Text, out thresholdcasb);

OleDbConnection kon = new OleDbConnection(koneksinectar);
DataTable dt = new DataTable();

OleDbDataAdapter adapter = new OleDbDataAdapter("select [WSID], [CasA], [CasB] from [Sheet1$]", kon);
DataSet coba = new DataSet();
adapter.Fill(coba);

var table = coba.Tables[0];
var view = new DataView(table);

if (CasAChk.Checked)
{
if (CasA.Text.Length > 0)
{

view.RowFilter = string.Format("[CasA] = '{0}'", thresholdcasa);
}
}
else if (CasBChk.Checked)
{
if (CasB.Text.Length > 0)
{
view.RowFilter = string.Format("[CasB] ='{0}'", thresholdcasb);
}
}

ViewNectarGV.DataSource = view;

Answer

You are building your RowFilter in an if... else if statement, hence only one code block or the other can be executed. You need to build a dynamic filter which appends all columns you wish to filter by, joined by an OR. Largely borrowed from this answer, try the following:

int temp = 0;
StringBuilder sb = new StringBuilder();

if (CasAChk.Checked && Int32.TryParse(CasA.Text, out temp))
{
    sb.Append(string.Format("[CasA] = '{0}'", temp));
}

if (CasBChk.Checked && Int32.TryParse(CasB.Text, out temp))
{
    if (sb.Length > 0)
    {
        sb.Append(" OR ");
    }

    sb.Append(string.Format("[CasB] = '{0}'", temp));
}

view.RowFilter = sb.ToString();

ViewNectarGV.DataSource = view;
Comments