In this article I am going to discuss how to use DataBinder.Eval in DataGrid and how to bind more than one properties to any control.
First of all you will learn how to fatch the record from the database and bind to DataGrid in ASP.Net.
Suppose we have a table name 'Puru_test_Employee' into my database like as follows:
Figure 1: My table name Puru_test_Employee in my database.
Step 1: Drag a DataGrid control from toolbar and drop on page or directlly write as follows:
<asp:DataGrid ID="DataGrid1" runat="server"></asp:DataGrid>
Step 2: Write the following code on your default.aspx.cs page
private void ShowFavoriteArticles()
{
SqlConnection con = new SqlConnection();
SqlCommand cmd = new SqlCommand();
con = new SqlConnection("Data Source=testServer;Initial Catalog=mydatabase; uid=sa;pwd=wintellect");
cmd.Connection = con;
cmd.CommandText = "Select * from Puru_test_Employee";
con.Open();
DataGrid1.DataSource = cmd.ExecuteReader();
DataGrid1.DataBind();
con.Close();
}
And call this method on page_load like as follows:
protected void Page_Load(object sender, EventArgs e)
{
ShowFavoriteArticles();
}
Output: You will get the following output.
Figure 2:
Now you can see how to bind the DataBinder.Eval as follows:
<asp:DataGrid ID="DataGrid1" runat="server" DataKeyField="EmplayeeId" AutoGenerateColumns="False" ShowHeader="true" CellPadding="5">
<Columns>
<asp:BoundColumn DataField="EmplayeeId" HeaderText="Emplayee Id" />
<asp:TemplateColumn HeaderText="Employee Name">
<ItemTemplate>
<asp:HyperLink ID="HyperLinkThread" runat="server" Text='<%#DataBinder.Eval(Container.DataItem,"EmployeeName")%>'
NavigateUrl='<%#GetDetail(DataBinder.Eval(Container.DataItem,"EmplayeeId"),
DataBinder.Eval(Container.DataItem,"EmployeeName"),DataBinder.Eval(Container.DataItem,"ActiveStatus"))%>'/>
</ItemTemplate>
</asp:TemplateColumn>
<asp:BoundColumn DataField="ActiveStatus" HeaderText="Active Status" />
</Columns>
</asp:DataGrid>
And write the following method on default.aspx.cs page
public string GetDetail(object objEmplayeeId, object objEmployeeName, object objActiveStatus)
{
int EmplayeeId = int.Parse(objEmplayeeId.ToString());
string employeename = objEmployeeName.ToString();
bool ActiveStatus = (bool)objActiveStatus;
if (ActiveStatus == true)
{
return "http://www.emplayeerecord.com/Emplayee/EmplayeeDetail.aspx?EmplayeeId=" + EmplayeeId;
//Write the url which you want to make
}
else
return "http://www.c-sharpcorner.com/";
}