我使用以下代码禁用gridview中列名为test的行。除了第一行,一切正常。颜色不会应用于第一行。我哪里出错?我还想根据列名隐藏一列。
protected void gv_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (Hidden4.Value == "Data Present")
{
foreach (GridViewRow item in GdvTestData.Rows)
{
int a = GetColumnIndexByName(item, "test");
int b = GetColumnIndexByName(item, "id");
if (e.Row.RowType == DataControlRowType.DataRow)
{
string test = e.Row.Cells[a].Text;
foreach (TableCell cell in e.Row.Cells)
{
if (test == "Y")
{
cell.BackColor = Color.Gray;
e.Row.Attributes.Add("onmouseover", "alert('This data is for testing');");
}
}
e.Row.Cells[b].Visible = false;
}
}
}
}
答案 0 :(得分:0)
也许您对数据/业务逻辑和UI感到困惑。
RowDataBound事件每行都有效,因此您不需要循环gridview行。
您正在处理单元格内容,但您已将数据绑定到这些内容。所以:
<强> ASPX 强>
<asp:GridView runat="server" ID="gv" ...
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:Label runat="server" Text='<%# Eval("Test") %>' />
</ItemTemplate>
</asp:TemplateField>
...
代码背后
private void GrdBind()
{
// populate datatable
gv.DataSource = myDataTable;
gv.Databind();
}
数据绑定事件:
protected void gv_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (Hidden4.Value == "Data Present")
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
DataRow row = ((DataRowView)e.Row.DataItem).Row;
string test = row.Field<String>("Test");
if (test== "Y")
{
e.Row.Cells[0].BackColor = Color.Gray; // set your index
e.Row.Attributes.Add("onmouseover", "alert('This data is for testing');");
}
}
}
}
答案 1 :(得分:0)
你可以这样做。虽然我不明白你禁用一行是什么意思。
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
//check if the row is a datarow
if (e.Row.RowType == DataControlRowType.DataRow)
{
//cast the dataitem back to a datarowview
DataRowView row = e.Row.DataItem as DataRowView;
//find the column value in the row, not the cell text
string test = row["columnName"].ToString();
//check the value and if so apply backcolor
if (test == "Y")
{
e.Row.BackColor = Color.Red;
//or hide the row (no need to do this in Databind or OnPreRender)
e.Row.Visible = false;
}
}
}