Menu ▼



Posted By :
avatarDatta
Total Views : 726

DataList view control

Simple Example For DataList view control in ASP.NET

<div>
<table>
<asp:DataList ID="DataList1" runat="server" OnItemCommand="DataList1_ItemCommand">
<HeaderTemplate>
<tr>
<th></th>
<th>Eno</th>
<th>Ename</th>
<th>Salary</th>
</tr>
</HeaderTemplate>
<ItemTemplate>
<tr>
<td><asp:Button ID="btnEdit" Text="Edit" CommandName="cmdEdit" runat="server" /></td>
<td><%?#?DataBinder?.Eval(Container.DataItem,"eno") %></td>
<td><%#DataBinder.Eval(Container.DataItem,"ename") %></td>
<td><%#DataBinder.Eval(Container.DataItem,"sal") %></td>
</tr>
</ItemTemplate>
<EditItemTemplate>
<tr>
<td>
<asp:Button ID="btnUpdate" Text="Update" CommandName="cmdUpdate" runat="server" /> </td>
<td><asp:Button ID="btnCancel" Text="Cancel" CommandName="cmdCancel" runat="server" />
</td>
<td>
<asp:Label ID="lblEmpno" Text='<%#DataBinder.Eval(Container.DataItem,"eno") %>' runat="server" />
</td>
<td> <asp:TextBox ID="txtEname" Text='<%#DataBinder.Eval(Container.DataItem,"ename") %>' runat="server" /></td>
<td><asp:TextBox ID="txtEsal" Text='<%#DataBinder.Eval(Container.DataItem,"sal") %>' runat="server" /></td>
</tr>

</EditItemTemplate>
</asp:DataList>
</table>

.cs code

SqlConnection con = new SqlConnection("user id=sa;pwd=nanisqlserver;database=sample;server=.");
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack == false)
{
Filldata();
}
}

protected void Filldata()
{
SqlDataAdapter da = new SqlDataAdapter("select * from emp", con);
DataSet ds = new DataSet();
da.Fill(ds);
DataList1.DataSource = ds;
DataList1.DataBind();
}

protected void DataList1_ItemCommand(object source, DataListCommandEventArgs e)
{
if (e.CommandName == "cmdEdit")
{
DataList1.EditItemIndex = e.Item.ItemIndex;
Filldata();
}
else if(e.CommandName=="cmdUpdate")
{
Label l = (Label)e.Item.FindControl("lblEmpno");
int empno = int.Parse(l.Text);
TextBox t1 = (TextBox)e.Item.FindControl("txtEname");
string empname = t1.Text;
TextBox t2 = (TextBox)e.Item.FindControl("txtEsal");
double empsal = double.Parse(t2.Text);
con.Open();
string query = "update emp set ename='"+empname+"', sal='"+empsal+"' where eno='"+empno+"'";
SqlCommand cmd = new SqlCommand(query, con);
cmd.ExecuteNonQuery();
DataList1.EditItemIndex = -1;
Filldata();
con.Close();
}
else if(e.CommandName=="cmdCancel")
{
DataList1.EditItemIndex=-1;
Filldata();
}
}
}





comments powered by Disqus


Search dotnetlearners.com