简体   繁体   English

C#遍历DataTable中的行

[英]C# Iterate through rows in a DataTable

I'm trying to Iterate through rows in a 2 column table to check 1 field in each row against a Name. 我正在尝试遍历2列表中的行,以对照名称检查每行中的1个字段。 Once found I want to code to assign the corresponding Number to the OurNumber variable, and break out of the loop by setting GotTheNumber to true. 找到后,我想编写代码以将相应的Number分配给OurNumber变量,并通过将GotTheNumber设置为true来打破循环。

Below is the code I'm using: 以下是我正在使用的代码:

    private void BtnDelete_Click(object sender, EventArgs e)// Sends to ConfirmDeleteEMP Form 
    {            
        ConfirmDeleteEMP form = new ConfirmDeleteEMP();
        DataTable table = new DataTable();
        string connstring = @"Provider = Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|\\HoliPlanData.accdb;Persist Security Info=False";
        using (OleDbConnection conn = new OleDbConnection(connstring))
        {
            string query = "SELECT PayrollNo, (FirstName + ' ' + LastName) AS NAME FROM [Employee]";                 
            OleDbDataAdapter adapter = new OleDbDataAdapter(query, conn);
            adapter.Fill(table);                                        
        }

        string SelectedName = DropBoxEmp.Text;            
        bool GotTheNumber = false;
        int OurNumber = 0;
        while (!GotTheNumber)
        {
            foreach (DataRow ThisRow in table.Rows)
            {
                if (SelectedName = (table.Rows[ThisRow])) 
                {
                    OurNumber = ///THATNUMBER///;
                    GotTheNumber = true;
                }  
            }
        }

        MessageBox.Show(SelectedName);
        var GoodNumber = (table.Rows[OurNumber]["PayrollNo"].ToString());
        form.PassValueName = SelectedName;
        form.PassSelectedPayroll = GoodNumber;               
        form.Tag = this;
        form.Show(this);
        Hide();
    }

I don't know where to go from the If statement, so any help would be greatly appreciated. 我不知道从If语句去哪里,所以将不胜感激任何帮助。

Looping through the rows in your client program is exactly what you don't want to do. 遍历客户程序中的行确实是您想要的。 Let the database do that work for you. 让数据库为您完成这项工作。 Try this: 尝试这个:

private void BtnDelete_Click(object sender, EventArgs e)// Sends to ConfirmDeleteEMP Form 
{     
    object result;       
    string query = "SELECT PayrollNo FROM [Employee] WHERE FirstName + ' ' + LastName = ?"; 
    string connstring = @"Provider = Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|\\HoliPlanData.accdb;Persist Security Info=False";

    using (OleDbConnection conn = new OleDbConnection(connstring))
    using (OleDbCommand cmd = new OleDbCommand(query, conn))
    {
        //guessing at type and length here
        cmd.Parameters.Add("?", OleDbType.VarWChar, 50).Value = DropBoxEmp.Text;

        conn.Open();
        result = cmd.ExecuteScalar();                                        
    }

    if (result != null && result != DBNull.Value)
    {
        ConfirmDeleteEMP form = new ConfirmDeleteEMP();
        form.PassValueName = DropBoxEmp.Text;
        form.PassSelectedPayroll = (int)result;
        form.Tag = this;

        form.Show(this);
        Hide();
    }                    
}

If you really want to loop through the rows against all reason (it's slower, requires writing more code, and it's more error-prone), you can do this: 如果您确实想在所有原因下遍历行(速度较慢,需要编写更多代码,并且更容易出错),则可以执行以下操作:

private void BtnDelete_Click(object sender, EventArgs e)// Sends to ConfirmDeleteEMP Form 
{                   
    DataTable table = new DataTable();
    string query = "SELECT PayrollNo, (FirstName + ' ' + LastName) AS NAME FROM [Employee]"; 
    string connstring = @"Provider = Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|\\HoliPlanData.accdb;Persist Security Info=False";
    using (OleDbConnection conn = new OleDbConnection(connstring))
    {                    
        OleDbDataAdapter adapter = new OleDbDataAdapter(query, conn);
        adapter.Fill(table);                                        
    }

    int PayrollNumber = 0;
    foreach (DataRow ThisRow in table.Rows)
    {
        if (DropBoxEmp.Text == ThisRow["NAME"])
        {
            PayrollNumber = (int)ThisRow["PayrollNo"];
            break;
        }  
    }
    //the whole loop could also be consolidated to this:
    //PayrollNumber = (int)table.Rows.First(r => r["NAME"] == DropBoxEmp.Text)["PayrollNo"];

    ConfirmDeleteEMP form = new ConfirmDeleteEMP();
    form.PassValueName = DropBoxEmp.Text;
    form.PassSelectedPayroll = PayrollNumber ;               
    form.Tag = this;
    form.Show(this);
    Hide();
}

Hm, hard to guess what exactly your problem is. 嗯,很难猜出你到底是什么问题。 But I think you just want to get the PayrollNo from the current row, aren't you? 但是我认为您只想从当前行中获取PayrollNo,不是吗?

Regarding the line further down ... 关于进一步下降的线...

var GoodNumber = (table.Rows[OurNumber]["PayrollNo"].ToString());

... I think you could just call: ...我想您可以致电:

if (...)
{
    OurNumber = ThisRow["PayrollNo"].ToString();
    GotTheNumber = true;
}

However , I have no clue what you are doing with the following if-condition and if this really does what you want it to do: 但是 ,我不知道您如何使用以下if条件以及是否确实满足您的要求:

if (SelectedName = (table.Rows[ThisRow]))
{
...
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM