[英]Replace Database value at the time of Gridview binding using c# asp.net
我正在使用c#和asp.net在Gridview中显示一些数据库值。在绑定到Grid视图中之前,我需要通过保持一些条件来更改值。我在下面解释我的代码。
HealthComment.aspx:
<asp:GridView ID="comnt_Gridview" runat="server" AutoGenerateColumns="false" Width="100%" CssClass="table table-striped table-bordered margin-top-zero" OnSelectedIndexChanged="comnt_Gridview_OnSelectedIndexChanged" onrowdeleting="comnt_Gridview_RowDeleting" DataKeyNames="Bnr_ID" >
<Columns>
<asp:TemplateField HeaderText="Sl. No" ItemStyle-CssClass="col-md-1 col-sm-1">
<ItemTemplate>
<%# Container.DataItemIndex + 1 %>
/ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Health ID" ItemStyle-CssClass="col-md-1 col-sm-1" ItemStyle-HorizontalAlign="Center">
<ItemTemplate>
<asp:Label ID="healthid" runat="server" Text='<%#Eval("Health_ID") %>'></asp:Label>
</ItemTemplate>
<asp:TemplateField HeaderText="Status" ItemStyle-CssClass="col-md-1 col-sm-1" ItemStyle-HorizontalAlign="Center">
<ItemTemplate>
<asp:Label ID="Url" runat="server" Text='<%#Eval("Health_Comment_Status") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
HealthComment.aspx.cs:
comnt_Gridview.DataSource = objhealthCommentBL.getHealthCommentDetails();
comnt_Gridview.DataBind();
healthCommentBL.cs:
private healthCommentDL objhealthCommentDL = new healthCommentDL();
public DataTable getHealthCommentDetails()
{
try
{
DataSet ds = objhealthCommentDL.getHealthCommentDetails();
DataTable dt = ds.Tables[0];
return dt;
}
catch (Exception e)
{
throw e;
}
}
healthCommentDL.cs:
SqlConnection con = new SqlConnection(CmVar.convar);
public DataSet getHealthCommentDetails()
{
try
{
con.Open();
DataSet ds = new DataSet();
string sql = "SELECT Health_Comment_ID,Health_ID,Health_Comment_Status from T_Health_Comment";
sql += " order by Bnr_ID ASC ";
SqlCommand cmd = new SqlCommand(sql, con);
SqlDataAdapter objadp = new SqlDataAdapter(cmd);
objadp.Fill(ds);
return ds;
}
catch (Exception e)
{
throw e;
}
finally
{
con.Close();
con.Dispose();
}
}
在这里,我的要求是数据库中有两种类型的Health_Comment_Status --- ie-R and A
当状态为R
,Gridview将显示已Rejected
;当状态为A
,Gridview将显示已Accepted
。请帮助我这样做。谢谢。
读取行值RowDataBound并将其置于条件上
for (int i = 0; i < GridView2.Rows.Count; i++)
{
string Health_Comment_Status;
Health_Comment_Status = GridView2.Rows[i].Cells[3].Text; // here you go vr = the value of the cel
if (Health_Comment_Status == "R") // you can check for anything
{
GridView2.Rows[i].Cells[3].Text = "Rejected";
// you can format this cell
}
else
{
GridView2.Rows[i].Cells[3].Text = "Accepted";
}
}
您可以根据您的代码设置名称和项目索引。
您可以像这样使用C# 条件运算符简单地做到这一点:
<ItemTemplate>
<asp:Label ID="Url" runat="server"
Text='<%#Eval("Health_Comment_Status") == "R" ? "Rejected" : "Accepted" %>'></asp:Label>
</ItemTemplate>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.