使用C#向DataGridView显示多个数据



我想根据文本框的值I输入显示多个数据。我有:

之类的数据
WSID   CasA   CasB 
1234   200    100   
5678   300    200
0987   400    300
6543   500    400

如果我输入CASA TextBox = 200和Casb TextBox = 200,将显示WSID 1234和5678。我遇到了一些问题,如果我像上面的输入值一样,它只是显示CASB的WSID。谁能帮我吗?

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;

您在if... else if语句中构建了RowFilter,因此只能执行一个代码块或另一个代码块。您需要构建一个动态过滤器,该过滤器附加了您要过滤的所有列,并由OR连接。从这个答案中借来的很大程度上,尝试以下内容:

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;

最新更新