Hi,
Whenever we want to manipulate the appearance on some cell based on the value of that cell, for example displaying negative numbers in a different color, and so on, then we use RowDataBound Event.
Example:
Write the following code in Default.aspx:
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false"
DataKeyNames="ProductId" onrowdatabound="GridView1_RowDataBound">
<Columns>
<asp:TemplateField HeaderText="SetEno">
<ItemTemplate>
<asp:DropDownList ID="ddlEmpid" runat="server" Width="90%" DataSourceID="SqlDataSource1" DataTextField="ProductId"
DataValueField="ProductId" >
</asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="ProductId" Visible="false">
<ItemTemplate>
<asp:Label ID="lblEmpNo" runat="server" Text='<%# Eval("ProductId") %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="ProductId" HeaderText="ProductId" ReadOnly="true" />
<asp:BoundField DataField="ProductName" HeaderText="ProductName" />
</Columns>
</asp:GridView>
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:MyConnection %>"
SelectCommand="SELECT [ProductId] FROM ProductsMvc"></asp:SqlDataSource>
Write the following code in Default.aspx.cs:
SqlConnection con;
protected void Page_Load(object sender, EventArgs e)
{
string conection;
conection = System.Configuration.ConfigurationManager.ConnectionStrings["MyConnection"].ConnectionString.ToString();
con = new SqlConnection(conection);
FillGrid();
}
protected void FillGrid()
{
SqlCommand cmd = new SqlCommand("select * from ProductsMvc", con);
con.Open();
GridView1.DataSource = cmd.ExecuteReader();
GridView1.DataBind();
con.Close();
}
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
DropDownList ddl = (DropDownList)e.Row.FindControl("ddlEmpid");
Label lblEmpid = ((Label)e.Row.FindControl("lblEmpNo"));
e.Row.Cells[3].ForeColor = Color.Red;
string x = lblEmpid.Text.ToString().Trim();
ddl.SelectedValue = x;
}
}
You can modify the code in roeDataBound event according to your requirement.
Thanks,
Shree M.
Kavya Shree Mandapalli
Prabu_Spark, if this helps please login to Mark As Answer. | Alert Moderator