Quantcast
Channel: Engineers Press » ASP.NET
Viewing all articles
Browse latest Browse all 2

ASP.NET : Customizing Datalist control of ASP.NET web forms

$
0
0

In the last few days there are all basic programming stuff posted on this blog and now i want to step this up and post something a bit more advanced that will be helpful to more real world developers that are facing problems in customizing the datalist control of ASP.NET. This post would provide some insights on how to customize datalist control and using that information  you can customize it to the level you would like.

so lets start off with how would our result form look like

Datalist Customization result form

Datalist Customization result form

This is our resulting form after we finish the tutorial in the post (you can add your own css as i am not going to go through the css or any designing part in this post).

Now the tasks we have to do to get this type of datalist Customization are:

  • Put an image button for the edit function.
  • On the click of edit button we have to feed in the data to the textbox controls and input fields
  • implementing custom paging in our datalist control

So lets first start off with the first task Image button for the edit function  in our Datalist control of ASP.NET.

For doing this we have to do a bit of coding in the .aspx part of our page like the given coding:


<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
 <h1>
 Edit and View Records</h1>
 <table style="width: 95%; height: 222px;">
 <tr>
 <td class="style3">
 First Name:
 </td>
 <td class="style4">
 <asp:TextBox ID="txtFirstName" runat="server"></asp:TextBox>
 </td>
 <td class="style1">
 <asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server"
 ErrorMessage="First Name is required" ForeColor="Red" ControlToValidate="txtFirstName" ValidationGroup="InsertData"></asp:RequiredFieldValidator>
 <asp:Label ID="Label1" runat="server" Visible="False"></asp:Label>
 </td>
 </tr>
 <tr>
 <td class="style3">
 Last Name:
 </td>
 <td class="style4">
 <asp:TextBox ID="txtLastName" runat="server"></asp:TextBox>
 </td>
 <td class="style1">
 <asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="server"
 ErrorMessage="Last Name is required" ForeColor="Red" ControlToValidate="txtLastName" ValidationGroup="InsertData"></asp:RequiredFieldValidator>
 </td>
 </tr>
 <tr>
 <td class="style3">
 Maths Marks:
 </td>
 <td class="style4">
 <asp:TextBox ID="txtMaths" runat="server"></asp:TextBox>
 </td>
 <td class="style1">
 <asp:RequiredFieldValidator ID="RequiredFieldValidator3" runat="server"
 ErrorMessage="Please input the science marks of the student"
 ControlToValidate="txtMaths" ForeColor="Red" ValidationGroup="InsertData" ></asp:RequiredFieldValidator>
 </td>
 </tr>
 <tr>
 <td class="style3">
 Science Marks:
 </td>
 <td class="style4">
 <asp:TextBox ID="txtScience" runat="server"></asp:TextBox>
 </td>
 <td class="style1">
 <asp:RequiredFieldValidator ID="RequiredFieldValidator4" runat="server"
 ErrorMessage="Please input the maths marks of the student" ForeColor="Red" ControlToValidate="txtScience" ValidationGroup="InsertData"></asp:RequiredFieldValidator>
 </td>
 </tr>
 <tr>
 <td class="style5">
 <asp:Label runat="server" ID="lblMessage" Font-Bold="True" Font-Italic="False"
 Font-Names="Arial Narrow" Font-Overline="False" Font-Size="Small"
 Font-Strikeout="False" Font-Underline="False" ForeColor="#C80435"></asp:Label>
 </td>
 <td class="style5">
 <asp:Button ID="btnInsert" runat="server" OnClick="btnClick" Text="Modify Data"
 ValidationGroup="InsertData"
 OnClientClick="return confirm('Are you sure you want to insert this data ')"
 BorderColor="#CC0000" BorderStyle="Solid" />
 </td>
 <td class="style6">
 &nbsp;</td>
 </tr>
 </table>
 <br />
 <asp:Label ID="lblTotalEntries" runat="server" Font-Bold="False"
 Font-Italic="True" Font-Names="Gisha" ForeColor="#BB3311"
 ViewStateMode="Enabled"></asp:Label>
 <br />
 <br />
 <table width="100%">
 <tr>
 <td width="10%">
 <strong>ID</strong>
 </td>
 <td width="15%">
 <strong>First Name</strong>
 </td>
 <td width="15%">
 <strong>Last Name</strong>
 </td>
 <td width="10%">
 <strong>Maths</strong>
 </td>
 <td width="10%">
 <strong>Science</strong>
 </td>
 <td width="10%">
 <strong>Total</strong>
 </td>
 <td width="30%">
 <strong>Edit</strong>
 </td>
 <%--<td width="15%">
 <strong>Delete</strong>
 </td>--%>
 </tr>
 </table>
 <table width="100%">
 <tr>
 <asp:DataList ID="StudentDataList" runat="server" Width="100%"
 onitemcommand="StudentDataList_ItemCommand" >

 <ItemTemplate>
 <td width="10%">
 <asp:Label ID="lblID" runat="server" Text='<%#Eval("ID") %>' ></asp:Label>
 </td>
 <td width="15%">
 <asp:Label ID="lblFirstName" runat="server" Text='<%#Eval("FirstName") %>' ></asp:Label>
 </td>
 <td width="15%">
 <asp:Label ID="lblLastName" runat="server" Text='<%#Eval("LastName") %>' ></asp:Label>
 </td>
 <td width="10%">
 <asp:Label ID="lblMaths" runat="server" Text='<%#Eval("Maths") %>'></asp:Label>
 </td>
 <td width="10%">
 <asp:Label ID="lblScience" runat="server" Text='<%#Eval("Science") %>'></asp:Label>
 </td>
 <td width="10%">
 <asp:Label ID="lblTotal" runat="server" Text='<%#Eval("Total") %>'></asp:Label>
 </td>
 <td width="30%">
<asp:ImageButton ID="EditButton" CommandName="Edit" CommandArgument='<%#Eval("ID") %>' runat="server" ImageUrl="~/Images/Edit.jpg" ToolTip="Edit" Height="20px" Width="20px" OnClientClick="return confirm('do you really want To edit the data')" />

</td>
</ItemTemplate>

</asp:DataList>
 </tr>
 <tr><td><asp:LinkButton ID="lbtnPrevious" runat="server" Text="Previous"
 onclick="lbtnPrevious_Click"></asp:LinkButton></td>
 <td><asp:LinkButton ID="lbtnNext" runat="server" Text="Next"
 onclick="lbtnNext_Click"></asp:LinkButton></td></tr>
 </table>

</asp:Content>

In the given code we can see that on line 130 we placed the image button inside the datalist control code and in the line 137 to 140 we we created the previous and next buttons for developing the paging part of the datalist control of ASP.NET . We also created the complete form for sending the data to the textboxes from the datalist on the click of edit button.

Now we have to perform the coding and learn how to get the data out of the rows of the datalist and fill that in the textbox controls. In this step we need to fill Datalist control data in ASP.NET textbox control.

now lets move on to the next task of our post and let’s look at the code for getting the idea and learning how to get the data out of the rows into the textbox controls and how to perform paging in the datalist control.

Lets have a look at our codebehind file of this design that we used to perform the required tasks:


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;

public partial class _Default : System.Web.UI.Page
{

 SqlConnection con = new SqlConnection(ConfigurationManager.AppSettings["KK"].ToString());
 protected void Page_Load(object sender, EventArgs e)
 {
 try
 {
 btnInsert.OnClientClick = "return confirm('Please select a record to modify by clicking select button first')";

 if (!IsPostBack)
 {
 ViewData();
 }

}
 catch(Exception)
 {
 Response.Redirect("~/LoginHelp/Login.aspx");
 }
 }
 public int CurrentPage
 {
 get
 {
 object o = this.ViewState["_CurrentPage"];
 if (o == null) return 0;
 else
 return (int)o;
 }
 set
 {
 this.ViewState["_CurrentPage"] = value;
 }
 }

protected void ViewData()
 {
 PagedDataSource page = new PagedDataSource();
 try
 {
 DataSet ds = new DataSet();
 string viewdata = "select * from dbo.student";
 SqlDataAdapter StudentDataAdapter = new SqlDataAdapter(viewdata, con);
 StudentDataAdapter.Fill(ds);
 page.AllowPaging = true;
 page.DataSource = ds.Tables[0].DefaultView;
 page.PageSize = 5;
 page.CurrentPageIndex = CurrentPage;

lbtnNext.Enabled = !page.IsLastPage;
 lbtnPrevious.Enabled = !page.IsFirstPage;
 StudentDataList.DataSource = page;
 StudentDataList.DataKeyField = "ID";
 StudentDataList.DataBind();
 lblTotalEntries.Text = "Total number of entries in system right now are : " + (int)ds.Tables[0].Rows.Count;
 }
 catch (Exception ex)
 {

lblMessage.Text = "error is" + ex;

}

 }
 protected void btnClick(object sender, EventArgs e)
 {
 lblMessage.Text = "";

if (Page.IsValid)
 {
 try
 {
 if (btnInsert.Text == "Modify Data")
 {
 if (lblId.Text == "")
 {
 lblMessage.Text = "Please select a record from below table to modify ";

 }
 else
 {
 lblMessage.Text = "";
 DataSet ds = new DataSet();
 string viewdata = "select * from dbo.student";
 SqlDataAdapter StudentDataAdapter = new SqlDataAdapter(viewdata, con);
 StudentDataAdapter.Fill(ds);
 con.Open();
 SqlCommand cmd = new SqlCommand("update dbo.student set FirstName='" + txtFirstName.Text.ToString() + "',LastName='" + txtLastName.Text.ToString() + "',Maths=" + Convert.ToInt32(txtMaths.Text) + ",Science=" + Convert.ToInt32(txtScience.Text) + " where ID='" + lblId.Text + "' ", con);

cmd.ExecuteNonQuery();
 txtFirstName.Text = "";
 txtLastName.Text = "";
 txtMaths.Text = "";
 txtScience.Text = "";

 lblMessage.Text = "Data Modified";
 btnInsert.OnClientClick = "return confirm('do you really want to Modify the data??')";
 }
 }

ViewData();
 }
 catch (Exception ex1)
 {

lblMessage.Text =ex1.Message;
 }
 }
 }

protected void StudentDataList_ItemCommand(object source, DataListCommandEventArgs e)
 {
 try
 {
 lblMessage.Text = "";
 string id = e.CommandArgument.ToString();
 if (e.CommandName == "Delete")
 {
 con.Open();

string sqlcmd = "delete from student where ID='" + id + "'";
 SqlCommand cmd = new SqlCommand(sqlcmd, con);

cmd.ExecuteNonQuery();
 lblMessage.Text = "Row Deleted";
 ViewData();
 }
 else if (e.CommandName == "Edit")
 {

 Label lbl = (Label)StudentDataList.Items[e.Item.ItemIndex].FindControl("lblID");
 int IDNumber = Convert.ToInt32(lbl.Text);

lblId.Text = IDNumber.ToString();

SqlDataReader dr;

 SqlCommand comm2 = new SqlCommand("SELECT FirstName, LastName, Maths, Science from dbo.Student WHERE ID='" + lblId.Text + "'");
 con.Open();
 comm2.Connection = con;

dr = comm2.ExecuteReader();

while (dr.Read())
 {
 txtFirstName.Text = dr["FirstName"].ToString();
 txtLastName.Text = dr["LastName"].ToString();
 txtMaths.Text = dr["Maths"].ToString();
 txtScience.Text = dr["Science"].ToString();
 }
 dr.Close();
 dr.Dispose();
 con.Close();
 ViewData();
 btnInsert.Text = "Modify Data";
 btnInsert.OnClientClick = "return confirm('do you really want to modify the data??')";

 }

 }
 catch (Exception Ex)
 {
 StudentDataList.EditItemIndex = -1;
 ViewData();
 lblMessage.Text = Ex.Message;
 }
 }

protected void lbtnPrevious_Click(object sender, EventArgs e)
 {
 lblMessage.Text = "";
 try
 {
 CurrentPage -= 1;
 ViewData();
 }
 catch (Exception ex)
 {
 lblMessage.Text = ex.Message;
 }
 }
 protected void lbtnNext_Click(object sender, EventArgs e)
 {
 lblMessage.Text = "";
 try
 {
 CurrentPage += 1;
 ViewData();
 }
 catch (Exception ex)
 {
 lblMessage.Text = ex.Message;
 }
 }
 }

In this source code of the code behind file of our ASP.NET web form we have a number of functions that perform very important tasks in our web form and first of them are ViewData function.

Viewdata function in our program is being used to bind the data to our dataset through sql server to our datalist you can see the code for it above.

Other functions are for paging and finding the SNo or id of the row on which the edit button is clicked which can be found in the function StudentDataList_ItemCommand on line number 144. The other part of the code is self explanatory.

The code in this post is for only demonstration and learning purpose and i didn’t thought about any standards while writing this code.

Thanks and if you have any questions or queries. Please comment



Viewing all articles
Browse latest Browse all 2

Latest Images

Trending Articles





Latest Images