2017-08-07 158 views
-1

我在嘗試創建gridview的自定義設置時遇到問題。我有一個數據庫設置如下:用戶|顏色| TempID。我希望能夠根據列表中顯示的用戶名稱更改顏色gridview。所以我將用戶Marcus添加到數據庫中,顏色爲#fef100。但是,當我嘗試拉入設置時,我得到了這個:system.data.datarow,而不是用戶名marcus。下面是代碼ASP.NET Webform自定義設置

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

它應該是'tools13.Rows [0] [0] .ToString()' – hardkoded

回答

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()); 
    } 
} 

tools13.Rows.Count > 0需要確保當用戶沒有顏色=空的DataTable你沒有得到一個index out of bounds

+0

非常感謝!無法工作,我感到非常沮喪。你的解決方案就像一個魅力。 – Marcus