循环数据表,用于为字符串赋值

时间:2016-05-05 12:06:58

标签: c# asp.net gridview datatable

我有一个gridview,其中有多个columnsrows

调试时会生成datatable,如下所示

Datatable

及其查询

DataTable dttable2 = new DataTable();
    dttable2 = CF.ExecuteDT("select cr.Mkey, cr.Rating1,cr.Rating2,cr.Rating3,cr.Rating4 from p_emp_Company_Rating cr  "+
                            "join p_emp_Exit_Interview ei on ei.Mkey=cr.Mkey where ei.mkey='" + HidMKey.Value + "'");

我想循环它,因为它包含行。

我尝试使用下面的代码,但它一次又一次出现。

string strgrid1 = string.Empty;

    if (dttable2.Rows.Count > 0)
    { 
        /** Job security **/
        if (dttable2.Rows[0]["Rating1"].ToString() == "Y")
        {
            strgrid1 = "Poor";
        }
        if (dttable2.Rows[0]["Rating2"].ToString() == "Y")
        {
            strgrid1 = "Satisfactory";
        }
        if (dttable2.Rows[0]["Rating3"].ToString() == "Y")
        {
            strgrid1 = "Good";
        }
        if (dttable2.Rows[0]["Rating4"].ToString() == "Y")
        {
            strgrid1 = "Excellent";
        }
    }

以下是gridview的截图

Grid

如何循环呢?

2 个答案:

答案 0 :(得分:3)

尝试使用foreach循环而不是if语句。

string strgrid1 = string.Empty;

foreach (DataRow row in dttable2.Rows)
{ 
    /** Job security **/
    if (row["Rating1"].ToString() == "Y")
    {
        strgrid1 = "Poor";
    }
    if (row["Rating2"].ToString() == "Y")
    {
        strgrid1 = "Satisfactory";
    }
    if (row["Rating3"].ToString() == "Y")
    {
        strgrid1 = "Good";
    }
    if (row["Rating4"].ToString() == "Y")
    {
        strgrid1 = "Excellent";
    }
}

答案 1 :(得分:2)

您也可以尝试使用For Loop来获得所需的效果。

string strgrid1 = string.Empty;

if (dttable2.Rows.Count > 0)
{ 
    /** Job security **/
    for(int i = 0; i < dttable2.Rows.Count - 1; i++)
    {
       if (dttable2.Rows[i]["Rating1"].ToString() == "Y")
       {
        strgrid1 = "Poor";
       }
       if (dttable2.Rows[i]["Rating2"].ToString() == "Y")
       {
        strgrid1 = "Satisfactory";
       }
       if (dttable2.Rows[i]["Rating3"].ToString() == "Y")
       {
        strgrid1 = "Good";
       }
       if (dttable2.Rows[i]["Rating4"].ToString() == "Y")
       {
        strgrid1 = "Excellent";
       }
    }
}