数据表在调用时为字符串分配错误的值

时间:2016-05-06 05:35:17

标签: c# html asp.net gridview datatable

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

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

Datatable

在html表格中为第一行和第二行分配值时,我将其称为

StrPriBody = StrPriBody + "<table style='width: 100%; height: 53px' border='1'><tr> " +
            "<td style='width: 100px; height: 14px;background-color:" + strcolordet + " ;white-space:nowrap'><strong>Job Security </strong></td> " +
            "<td style='width: 100px; height: 14px;background-color:" + strcolordet + "'>" + strgrid1 + "</td><br /> " +
        "<td style='width: 100px; height: 14px;background-color:" + strcolordet + " ;white-space:nowrap'><strong>Opportunity for Promotion </strong></td> " +
            "<td style='width: 100px; height: 14px;background-color:" + strcolordet + "'>" + strgrid1 + "</td></tr></table> ";

来自datatable代码

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";
        }
    }

但是当我看到strgrid1的值时,它始终为Excellent。为什么??

分配错误的值。 gridview的屏幕截图如下。我希望看到那些经过检查的值的正确值。

GRID

请建议为什么它采取了错误的值

更新

数据表代码: -

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 + "'");

1 个答案:

答案 0 :(得分:1)

你正在使用一个变量strgrid1来构建整个表,当你这样做时,它只有一个值,即最后一个值。

您需要在循环中构建行:

StrPriBody = StrPriBody + "<table style='width: 100%; height: 53px' border='1'><tr> ";

List<string> titles = new List<string>()
{
    "Job Security", "Opportunity for Promotion" // etc..
};
Queue<string> titlesQueue = new Queue<string>(titles);

foreach (DataRow row in dttable2.Rows)
{
    string rowTitle = ""; // GET THE TITLE FROM SOME ARRAY OR LIST
    /** Job security **/
    if (row["Rating4"].ToString() == "Y")
    {
        strgrid1 = "Excellent";
    }
    else if (row["Rating3"].ToString() == "Y")
    {
        strgrid1 = "Good";
    }
    else if (row["Rating2"].ToString() == "Y")
    {
        strgrid1 = "Satisfactory";
    }

    else if (row["Rating1"].ToString() == "Y")
    {
        strgrid1 = "Poor";
    }      

    StrPriBody = StrPriBody +
        "<td style='width: 100px; height: 14px;background-color:" + strcolordet + " ;white-space:nowrap'><strong>" + titlesQueue.Dequeue() + "</strong></td> " +
        "<td style='width: 100px; height: 14px;background-color:" + strcolordet + "'>" + strgrid1 + "</td><br /> ";
}

StrPriBody += "<table/>";