我有一个网格视图,它填充了我的SQL数据阅读器
网格视图:
<asp:GridView ID="gridviewALL" runat="server" OnItemDataBound="Search_ItemDataBound">
</asp:GridView>
SQL数据阅读器:
SqlCommand cmd = new SqlCommand("SELECT en.dpCreatedDT AS 'Time Received', en.enStatusCH AS 'Status', en.enNotificationNoNI AS 'LSBUD Ref', cm.cmpersonfirstch AS 'First Name', cm.cmPersonLastCH AS 'Last Name', cm.cmcompanynamech AS 'Company' FROM dp_enquiry en JOIN dp_caller_master cm ON (en.encmcallerkeyfk = cm.cmCallerKeyNI) WHERE en.ennotificationnoni = @JobnoALL", conn);
try
{
SqlParameter search = new SqlParameter();
search.ParameterName = "@JobnoALL";
search.Value = JobnoALL.Text.Trim();
cmd.Parameters.Add(search);
SqlDataReader dr = cmd.ExecuteReader();
DataTable dt = new DataTable();
dt.Load(dr);
gridviewALL.DataSource = dt;
gridviewALL.DataBind();
}
当文本等于某个值时,我正在尝试更改网格视图中单元格的格式,我之前使用listview完成了此操作,但Gridview步骤似乎有所不同。我有以下似乎没有任何建议吗?
private void Search_ItemDataBound(object sender, System.Web.UI.WebControls.DataGridItemEventArgs e)
{
string CurrentColumn = e.Item.Cells[1].Text;
if (CurrentColumn == "PROC")
{
e.Item.Cells[1].Text = "Creating PDF";
}
else if (CurrentColumn == "CLOS")
{
e.Item.Cells[1].Text = "Complete";
e.Item.Cells[1].ForeColor = System.Drawing.Color.Green;
}
}
答案 0 :(得分:2)
必须读取标题,您需要检查它是否为DataRow
: -
if (e.Row.RowType == DataControlRowType.DataRow)
{
string CurrentColumn = e.Item.Cells[1].Text;
//your code goes here..
}
另外,我建议您使用DataBinder.Eval方法来避免单元索引的硬编码,因为如果列的顺序发生变化,可能会导致错误。
string CurrentColumn = DataBinder.Eval(e.Row.DataItem, "yourColumnName").ToString();
<强>更新强>
只是注意到您使用的是ItemDataBound
,DataGrid
而不是Gridview
。请改用RowDataBound
事件: -
<asp:GridView ID="gridviewALL" runat="server" OnRowDataBound="gridviewALL_RowDataBound">
</asp:GridView>
您的rowDataBound事件应如下所示: -
protected void gridviewALL_RowDataBound(object sender, GridViewRowEventArgs e)
{
//your code here
}