尝试为gridview
创建自定义设置时出现问题。我有一个数据库设置如下:用户|颜色| TempID。我希望能够根据用户名在列表中显示时更改gridview
颜色。所以我将用户Marcus添加到数据库中,颜色为#fef100
。然而,当我尝试拉入设置时,我得到了这个:system.data.datarow而不是用户名marcus。以下是代码
protected void OnRowDataBound(object sender, GridViewRowEventArgs e)
{
string Settings = ConfigurationManager.ConnectionStrings["userthemes"].ConnectionString;
SqlConnection con13 = new SqlConnection(Settings);
SqlDataAdapter grid13 = new SqlDataAdapter("SELECT [User],[Colors], [TempID] FROM userthemes.dbo.[Colors]", con13);
DataTable tools13 = new DataTable();
grid13.Fill(tools13);
DataTable alltools13 = new DataTable();
GridView10.DataSource = tools13;
GridView10.DataBind();
Label9.Text = tools13.Rows[0].ToString();
foreach (DataRow row in tools13.Rows)
{
foreach (var item in row.ItemArray)
{
if (e.Row.Cells[1].Text == (tools13.Rows[0].ToString()))
{
e.Row.Cells[0].BackColor = System.Drawing.ColorTranslator.FromHtml(tools13.Rows[1].ToString());
e.Row.Cells[1].BackColor = System.Drawing.ColorTranslator.FromHtml(tools13.Rows[1].ToString());
e.Row.Cells[2].BackColor = System.Drawing.ColorTranslator.FromHtml(tools13.Rows[1].ToString());
e.Row.Cells[3].BackColor = System.Drawing.ColorTranslator.FromHtml(tools13.Rows[1].ToString());
e.Row.Cells[4].BackColor = System.Drawing.ColorTranslator.FromHtml(tools13.Rows[1].ToString());
e.Row.Cells[5].BackColor = System.Drawing.ColorTranslator.FromHtml(tools13.Rows[1].ToString());
e.Row.Cells[6].BackColor = System.Drawing.ColorTranslator.FromHtml(tools13.Rows[1].ToString());
e.Row.Cells[7].BackColor = System.Drawing.ColorTranslator.FromHtml(tools13.Rows[1].ToString());
e.Row.Cells[8].BackColor = System.Drawing.ColorTranslator.FromHtml(tools13.Rows[1].ToString());
e.Row.Cells[9].BackColor = System.Drawing.ColorTranslator.FromHtml(tools13.Rows[1].ToString());
e.Row.Cells[8].ForeColor = System.Drawing.ColorTranslator.FromHtml(tools13.Rows[1].ToString());
e.Row.Cells[9].ForeColor = System.Drawing.ColorTranslator.FromHtml(tools13.Rows[1].ToString());
}
}
}
}
答案 0 :(得分:0)
您已经在tools13
中循环所有行,您可以使用
e.Row.Cells[0].BackColor = System.Drawing.ColorTranslator.FromHtml(row["Colors"].ToString());
但是,由于用户可能只从查询返回一种颜色,因此您可以直接访问第一行而不使用foreach
循环。
if (e.Row.RowType == DataControlRowType.DataRow)
{
if (tools13.Rows.Count > 0)
{
e.Row.BackColor = ColorTranslator.FromHtml(tools13.Rows[0]["Colors"].ToString());
//or by column index instead of by name
e.Row.BackColor = ColorTranslator.FromHtml(tools13.Rows[0][1].ToString());
}
}
当用户没有Colors = empty DataTable时,需要tools13.Rows.Count > 0
以确保您没有获得index out of bounds
。