Friday, October 11, 2019

How to work with Datalist control in Asp.net


DataList Control In Asp.net

This Article explain the DataList Control and its use in Asp.net program

# DataList

  • To display data in multiple column
  • We can manipulate data
  • No default template
  • No paging
  • 7 templates can be used

The 7 templates which can be used are :

  1. ItemTemplate
  2. AlternatingTemplate
  3. HeaderTemplate
  4. FooterTemplate
  5. SeparatorTemplate
  6. EditItemTemplate
  7. SelectedItemTemplate

# DataList

File > New>project>visual C# >web>webfrm>empty(WebApllication 7)
*Add new item> webform

#Now make connection string in web.config


<configuration>
  <connectionStrings>
    <add name = "ps" connectionString="server=.\SQLEXPRESS; database=database name; integrated security=true"/>
</connectionStrings>
  <system.web>

# In design
Click on toolbox>Data > DataList
*On click on code page

private void List_Bind()
        {
            SqlDataAdapter adp = new SqlDataAdapter("select * from tbbook", ConfigurationManager.ConnectionStrings["ps"].ConnectionString);
            DataSet ds = new DataSet();
            adp.Fill(ds);
            DataList1.DataSource = ds;
            DataList1.DataBind();

        }

*Now call List_Bind in Page load

using System.Data;
using System.Data.SqlClient;
using System.Configuration;


namespace WebApplication7
{
    public partial class WebForm1 : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (Page.IsPostBack == false)
            {
                List_Bind();
            }

#Source code

<asp:DataList ID="DataList1" runat="server">
                <ItemTemplate>
                    <b>Title :</b><%#Eval ("BookTitle") %><br />
                    <b>Author :</b><%#Eval ("BookAuthor") %><br />
                    <b>Publisher :</b><%#Eval ("BookPublisher") %><br />
                    <b>Price :</b><%#Eval ("BookPrice") %><br />

                </ItemTemplate>
            </asp:DataList>

Click Right Click DataList > property> RepeatColumn=2
Now Click on arrow of DataList>Autoformat> choose any preferred format

#Now to Edit Command to edit data on webform when Executed

*Predefined Commands used
Edit – EditCommand
Cancel-CancelCommand
Delete-DeleteCommand
Update-UpdateCommand
Select-SelectCommand

<ItemTemplate>
                    <b>Title :</b><%#Eval ("BookTitle") %><br />
                    <b>Author :</b><%#Eval ("BookAuthor") %><br />
                    <b>Publisher :</b><%#Eval ("BookPublisher") %><br />
                    <b>Price :</b><%#Eval ("BookPrice") %><br />
                    <asp:LinkButton ID="lk" Text="Edit" CommandName="edit" runat="server" />
                </ItemTemplate>

# When Click on Edit when webform is executed, textbox should comes infront of Title, Author, Publisher, Price and infront of Edit Update and Cancel Button should comes.

</ItemTemplate>
                <EditItemTemplate>
                    <b>Title :</b><asp:TextBox ID="t1" Text='<%#Eval("BookTitle")%>' runat="server" />
                    <b>Author :</b><asp:TextBox ID="t2" Text='<%#Eval("BookAuthor")%>' runat="server" />
                    <b>Publisher :</b><asp:TextBox ID="t3" Text='<%#Eval("BookPublisher")%>' runat="server" />
                    <b>Price :</b><asp:TextBox ID="t4" Text='<%#Eval("BookPrice")%>' runat="server" />
                    <asp:LinkButton ID="lk1" Text="Update" CommandName="update" runat="server" />
                    <asp:LinkButton ID="lk2" Text="Cancel" CommandName="cancel" runat="server" />
                </EditItemTemplate>

# For edit (to edit selected record)

Now click on design >DataList property>Event icon
Now double Click on Editcommand in it

protected void DataList1_EditCommand(object source, DataListCommandEventArgs e)
        {
            DataList1.EditItemIndex = e.Item.ItemIndex;
            List_Bind();
        }
 If we write DataList1.EditItemIndex = 1; It will go to index 1. By default index of starts from 0,1,2,3

e.item = used for current item

#Now for Cancel

Design > DataList property >Event icon > Double click on Cancel command

protected void DataList1_CancelCommand(object source, DataListCommandEventArgs e)
        {
            DataList1.EditItemIndex = -1;
            List_Bind();
        }

DataList1.EditItemIndex = -1 (-1 is used because index -1 doesnot exit so when clicked on cancel all record will be displayed in itemtemplate)
During update , the 1 click for update is opened in edititemtemplate and rest in itemtemplate

# For Update

*Findcontrol- To find id required, e is 2nd parameter and to fetch data from DataList
* Design > DataList property >Event icon > Double click on Update command
DataList> Properties>DatakeyField=BookId

It makes an array named as datakeys and datakeys will be equal to number of records in table.It will fetch data from tbbook table. It can specify single column only in datakeyfield.

Note – We can update data by SqldataAdapter but use it when multiple records have to be updated for single sqlcommand can be used

protected void DataList1_UpdateCommand(object source, DataListCommandEventArgs e)
        {
            Int32 bid, prc;
            String tit, auth, pub;
            tit = ((TextBox)(e.Item.FindControl("t1"))).Text;
            auth = ((TextBox)(e.Item.FindControl("t2"))).Text;
            pub = ((TextBox)(e.Item.FindControl("t3"))).Text;
            prc = Convert.ToInt32(((TextBox)(e.Item.FindControl("t4"))).Text);
            bid = Convert.ToInt32(DataList1.DataKeys[e.Item.ItemIndex]);
            SqlConnection con = new SqlConnection();
            con.ConnectionString = ConfigurationManager.ConnectionStrings["ps"].ConnectionString;
            con.Open();
            SqlCommand cmd = new SqlCommand();
            cmd.CommandText = "update tbbook set BookTitle=@tit,BookAuthor=@auth,BookPublisher=@pub,BookPrice=@prc where BookId=@bid";
            cmd.Connection = con;
            cmd.Parameters.Add("@bid", SqlDbType.Int).Value = bid;
            cmd.Parameters.Add("@tit", SqlDbType.VarChar,50).Value = tit;
            cmd.Parameters.Add("@auth", SqlDbType.VarChar, 50).Value = auth;
            cmd.Parameters.Add("@pub", SqlDbType.VarChar, 50).Value = pub;
            cmd.Parameters.Add("@prc", SqlDbType.Int).Value = prc;
            cmd.ExecuteNonQuery();
            cmd.Dispose();
            DataList1.EditItemIndex = -1;
            List_Bind();

        }


No comments:

Post a Comment