I want to replace a gridview field depending if the value is null or blank. For example there are 4 fields, ID, Course, Mark 1 and Mark 2. The 3 headings are ID, Course and Mark. If mark1 is blank then it should automatically call mark2, however this ain't happening. This is the code I have used.
Code:
<%@ Page Language="C#" %>
<%@ Import Namespace="System.Data" %>
<%@ Import Namespace="System.Data.SqlClient" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">
protected void Page_Load(object sender, EventArgs e)
{
BindData();
//GridView1_RowDataBound();
}
public void BindData()
{
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["connBMC"].ConnectionString);
conn.Open();
SqlCommand cmd = conn.CreateCommand();
cmd.CommandText = "Select * from iftest";
SqlDataReader dr = cmd.ExecuteReader();
GridView1.DataSource = dr;
GridView1.DataBind();
conn.Close();
}
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
Label myLabel1 = (Label)e.Row.FindControl("lblMark1");
string text = myLabel1.Text;
Label myLabel2 = (Label)e.Row.FindControl("lblMark2");
if (text == null || text.Length < 1)
{
myLabel2.Visible = true;
}
}
}
</script>
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>Untitled Page</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:connBMC %>"
SelectCommand="SELECT * FROM [iftest]"></asp:SqlDataSource>
</div>
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False">
<Columns>
<asp:BoundField DataField="ID" HeaderText="ID" InsertVisible="False" ReadOnly="True"
SortExpression="ID" />
<asp:BoundField DataField="Course" HeaderText="Course" SortExpression="Course" />
<asp:TemplateField HeaderText="Mark">
<ItemTemplate>
<asp:Label ID="lblMark1" Text='<%# Eval("Mark1") %>' runat="server"></asp:Label>
<asp:Label ID="lblMark2" Text='<%# Eval("Mark2") %>' runat="server" Visible="False"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<asp:SqlDataSource ID="SqlDataSource2" runat="server" ConnectionString="<%$ ConnectionStrings:connBMC %>"
SelectCommand="SELECT * FROM [iftest]"></asp:SqlDataSource>
</form>
</body>
</html>