我使用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();
}
}
我的要求是数据库i.e-R and A
中有两种类型的Health_Comment_Status。当状态为R
时,Gridview将显示Rejected
,当状态为A
时Gridview将显示Accepted
。请帮我这样做。谢谢。
答案 0 :(得分:0)
读取行值RowDataBound并将其置于conditaion
答案 1 :(得分:0)
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";
}
}
您可以根据代码设置名称和项目索引。
答案 2 :(得分:0)
您可以使用C#Conditional Operator执行此操作: -
<ItemTemplate>
<asp:Label ID="Url" runat="server"
Text='<%#Eval("Health_Comment_Status") == "R" ? "Rejected" : "Accepted" %>'></asp:Label>
</ItemTemplate>