ASP.NET - Gridview and DataList

Asked By Badri
09-Aug-11 01:40 AM
i need full details for DataGridView and DataList
1. How to insert,update,deleting of text,images in the grid and list
2. how to access data from GridView and Datalist in different ways.
3. If any most commonly user property r functions of DataGridView and DataList.
  James H replied to Badri
09-Aug-11 02:00 AM
How to insert,update,deleting of text,images in the grid and list
For inserting record, i've put textboxes in footer row of GridView using ItemTemplate and FooterTemaplete.
http://4.bp.blogspot.com/_6FOczBbkX4I/SgsYR8u_qcI/AAAAAAAAAcI/ATqRxpyBaCI/s1600-h/0.JPG

Go to design view of aspx page and drag a GridView control from toolbox, click on smart tag of GridView and choose new datasource
http://4.bp.blogspot.com/_6FOczBbkX4I/SgsZxzf7AbI/AAAAAAAAAcQ/EG6KbGcZPzs/s1600-h/1.JPG
Select Database and click Ok
http://3.bp.blogspot.com/_6FOczBbkX4I/SgsaBru_G3I/AAAAAAAAAcY/22xzJnTd8dw/s1600-h/2.JPG 
In next screen, Enter your SqlServer name , username and password and pick Database name from the dropdown , Test the connection
 
http://4.bp.blogspot.com/_6FOczBbkX4I/Sgsafo8grcI/AAAAAAAAAcg/g75KlxkUwUs/s1600-h/3.JPG 
 In next screen, select the table name and fields , Click on Advance tab and check Generate Insert,Edit and Delete statements checkbox , alternatively you can specify your custom sql statements 
http://2.bp.blogspot.com/_6FOczBbkX4I/SgsbOl2SnfI/AAAAAAAAAcw/LCbNFEpE-cQ/s1600-h/4.JPG 
 http://1.bp.blogspot.com/_6FOczBbkX4I/SgsbT8g8iQI/AAAAAAAAAc4/791TNvs2tis/s1600-h/5.JPG
Click on ok to finish 
Check Enable Editing , enable deleting checkbox in gridView smart tag 
http://4.bp.blogspot.com/_6FOczBbkX4I/Sgsbk6IHTDI/AAAAAAAAAdA/xnGPxSr84FY/s1600-h/6.JPG
Now go to html source of page and define DatakeyNames field in gridview source
<asp:GridView ID="GridView1" runat="server" 
              AutoGenerateColumns="False" 
              DataKeyNames="ID"
              DataSourceID="SqlDataSource1" 
              OnRowDeleted="GridView1_RowDeleted" 
              OnRowUpdated="GridView1_RowUpdated" 
              ShowFooter="true" 
              OnRowCommand="GridView1_RowCommand">
</asp:GridView>
Remove the boundFields and put ItemTemplate and EditItemTemplate and labels and textboxs respectively, complete html source of page should look like this
<form id="form1" runat="server">
<div>
<asp:GridView ID="GridView1" runat="server" 
              AutoGenerateColumns="False" 
              DataKeyNames="ID"
              DataSourceID="SqlDataSource1" 
              OnRowDeleted="GridView1_RowDeleted" 
              OnRowUpdated="GridView1_RowUpdated" 
              ShowFooter="true" 
              OnRowCommand="GridView1_RowCommand">
<Columns>
    <asp:CommandField ShowDeleteButton="True" 
                      ShowEditButton="True" />
    <asp:TemplateField HeaderText="ID" SortExpression="ID">
    <ItemTemplate>
    <asp:Label ID="lblID" runat="server" 
                          Text='<%#Eval("ID") %>'>
    </asp:Label>
    </ItemTemplate>
    <FooterTemplate>
    <asp:Button ID="btnInsert" runat="server" 
                Text="Insert" CommandName="Add" />
    </FooterTemplate>
    </asp:TemplateField>
    
    <asp:TemplateField HeaderText="FirstName" 
                       SortExpression="FirstName">
    <ItemTemplate>
    <asp:Label ID="lblFirstName" runat="server" 
               Text='<%#Eval("FirstName") %>'>
    </asp:Label>
    </ItemTemplate>
    <EditItemTemplate>
    <asp:TextBox ID="txtFirstName" runat="server" 
                 Text='<%#Bind("FirstName") %>'>
    </asp:TextBox>
    </EditItemTemplate>
    <FooterTemplate>
    <asp:TextBox ID="txtFname" runat="server">
    </asp:TextBox>
    </FooterTemplate>
    </asp:TemplateField>
    
    <asp:TemplateField HeaderText="LastName" 
                       SortExpression="LastName">
    <ItemTemplate>
    <asp:Label ID="lblLastName" runat="server" 
               Text='<%#Eval("LastName") %>'>
    </asp:Label>
    </ItemTemplate>
    <EditItemTemplate>
    <asp:TextBox ID="txtLastName" runat="server" 
                 Text='<%#Bind("LastName") %>'>
    </asp:TextBox>
    </EditItemTemplate>
    <FooterTemplate>
    <asp:TextBox ID="txtLname" runat="server">
    </asp:TextBox>
    </FooterTemplate>
    </asp:TemplateField>
    
    <asp:TemplateField HeaderText="Department" 
                       SortExpression="Department">
    <ItemTemplate>
    <asp:Label ID="lblDepartment" runat="server" 
               Text='<%#Eval("Department") %>'>
    </asp:Label>
    </ItemTemplate>
    <EditItemTemplate>
    <asp:TextBox ID="txtDepartmentName" runat="server" 
                 Text='<%#Bind("Department") %>'>
    </asp:TextBox>
    </EditItemTemplate>
    <FooterTemplate>
    <asp:TextBox ID="txtDept" runat="server">
    </asp:TextBox>
    </FooterTemplate>
    </asp:TemplateField>
    
    <asp:TemplateField HeaderText="Location" 
                       SortExpression="Location">
    <ItemTemplate>
    <asp:Label ID="lblLocation" runat="server" 
               Text='<%#Eval("Location") %>'>
    </asp:Label>
    </ItemTemplate>
    <EditItemTemplate>
    <asp:TextBox ID="txtLocation" runat="server" 
                 Text='<%#Bind("Location") %>'>
    </asp:TextBox>
    </EditItemTemplate>
    <FooterTemplate>
    <asp:TextBox ID="txtLoc" runat="server">
    </asp:TextBox>
    </FooterTemplate>
    </asp:TemplateField>
</Columns>
</asp:GridView>

<asp:SqlDataSource ID="SqlDataSource1" runat="server" 
ConnectionString="<%$ ConnectionStrings:DBConString%>"
DeleteCommand="DELETE FROM [Employees] WHERE [ID] = @ID" 
InsertCommand="INSERT INTO [Employees] ([FirstName], 
[LastName],[Department], [Location]) 
VALUES (@FirstName, @LastName, @Department, @Location)"
SelectCommand="SELECT [ID], [FirstName], [LastName], 
[Department], [Location] FROM [Employees]"
UpdateCommand="UPDATE [Employees] SET 
[FirstName] = @FirstName, [LastName] = @LastName, 
[Department] = @Department, [Location] = @Location 
WHERE [ID] = @ID" OnInserted="SqlDataSource1_Inserted">

<DeleteParameters>
    <asp:Parameter Name="ID" Type="Int32" />
</DeleteParameters>
<UpdateParameters>
    <asp:Parameter Name="FirstName" Type="String" />
    <asp:Parameter Name="LastName" Type="String" />
    <asp:Parameter Name="Department" Type="String" />
    <asp:Parameter Name="Location" Type="String" />
    <asp:Parameter Name="ID" Type="Int32" />
</UpdateParameters>
<InsertParameters>
    <asp:Parameter Name="FirstName" Type="String" />
    <asp:Parameter Name="LastName" Type="String" />
    <asp:Parameter Name="Department" Type="String" />
    <asp:Parameter Name="Location" Type="String" />
</InsertParameters>
</asp:SqlDataSource>
<asp:Label ID="lblMessage" runat="server" 
           Font-Bold="True"></asp:Label><br />
</div>
</form>
Write this code in RowCommand Event of GridView in codebehind
C# code Behind
protected void GridView1_RowCommand
(object sender, GridViewCommandEventArgs e)
{
  if (e.CommandName == "Add")
  {
   string strFirstName = ((TextBox)
   GridView1.FooterRow.FindControl("txtFname")).Text;

   string strLastName = 
   ((TextBox)GridView1.FooterRow.FindControl
                         ("txtLname")).Text;

   string strDepartment = 
   ((TextBox)GridView1.FooterRow.FindControl
                            ("txtDept")).Text;
   string strLocation = ((TextBox)GridView1.FooterRow.
                          FindControl("txtLoc")).Text;
   //SqlDataSource1.InsertParameters.Clear();
   //SqlDataSource1.InsertParameters.Add
                       //("FirstName", strFirstName);
   //SqlDataSource1.InsertParameters.Add
                          //("LastName", strLastName);
   //SqlDataSource1.InsertParameters.Add
                         //("Department", strDepartment);
   //SqlDataSource1.InsertParameters.Add
                              //("Location", strLocation);

  SqlDataSource1.InsertParameters["FirstName"].DefaultValue 
                                             = strFirstName;
  SqlDataSource1.InsertParameters["LastName"].DefaultValue 
                                             = strLastName;
  SqlDataSource1.InsertParameters["Department"].DefaultValue 
                                             = strDepartment;
  SqlDataSource1.InsertParameters["Location"].DefaultValue
                                            = strLocation;
  SqlDataSource1.Insert();
  }
}

  dipa ahuja replied to Badri
09-Aug-11 03:29 AM
Binding gridview:

Add a class in your website and add an method in it.:

public static DataTable getdata()
{
  string conn = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
 
  SqlConnection con = new SqlConnection(conn);
  con.Open();
  string q = "select * from table1";
  SqlCommand comm = new SqlCommand(q, con);

  SqlDataAdapter da = new SqlDataAdapter(comm);
  DataTable dt = new DataTable();
  da.Fill(dt);
  return dt; 
}
Bind in .cs:
GridView1.DataSource = Class1.getdata();
GridView1.DataBind();
  dipa ahuja replied to Badri
09-Aug-11 03:31 AM
Answer 2: By default gridview doesn't have any inbuild functionality to insert records. but you can do it manually this way:


Untitled document
Step 1 : Add new template Field With the Required Controls:
 
<asp:TemplateField>
<FooterTemplate>
 Name:<asp:TextBox ID="txtname" runat="server" /><br />
 Gender :
 <asp:DropDownList ID="ddGender" runat="server">
   <asp:ListItem>Male</asp:ListItem>
   <asp:ListItem>Female</asp:ListItem>
 </asp:DropDownList>
       
  <asp:Button ID="btnInsert" runat="server" Text="Insert" OnClick="btnInsert_Click" />
</FooterTemplate>
</asp:TemplateField>
  
► Step 2 Implement the Button's Click event:
protected void btnInsert_Click(object sender, EventArgs e)
{
 string name = ((TextBox)GridView1.FooterRow.FindControl("txtname")).Text;
 string gender = ((DropDownList)GridView1.FooterRow.FindControl("ddGender")).SelectedValue;
  string ConnString = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
 SqlConnection conn = new SqlConnection(ConnString);
   
  conn.Open();
   
  string q = "insert into people (name,gender) values(@name,@gender)";
 SqlCommand comm = new SqlCommand(q,conn);
  comm.Parameters.AddWithValue("name", name);
 comm.Parameters.AddWithValue("gender", gender);
 comm.ExecuteNonQuery();
 conn.Close();
  BindGrid(); //Re-bind Gridview
}
  Vickey F replied to Badri
09-Aug-11 04:47 AM

DataList  = The appearance of the DataList control may be customized by setting the style properties for the different parts of the control.

The following table lists the different style properties.

AlternatingItemStyle: Specifies the style for alternating items in the DataList control.
EditItemStyle: Specifies the style for the item being edited in the DataList control.

FooterStyle: Specifies the style for the footer in the DataList control.

HeaderStyle: Specifies the style for the header in the DataList control.

ItemStyle: Specifies the style for the items in the DataList control.

SelectedItemStyle: Specifies the style for the selected item in the DataList control.

SeparatorStyle: Specifies the style for the separator between the items in the DataList control.

You can also show or hide different parts of the control. The following table lists the properties that control which parts are shown or hidden.

ShowFooter: Shows or hides the footer section of the DataList control.

ShowHeader: Shows or hides the header section of the DataList control.

The display direction of a DataList control can be vertical or horizontal. Set the RepeatDirection property to specify the display direction.

The layout of the DataList control is controlled with the RepeatLayout property. Setting this property to RepeatLayout.Table will display the DataList in a table format, while RepeatLayout.Flow displays the DataList without a
table structure.

Example- 

.aspx code

<asp:DataList ID=" dlMyCountry" runat="server">
<ItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%# Eval("Country_Code") %>'></asp:Label>
<asp:Label ID="Label2" runat="server" Text='<%# Eval("Country_Name") %>'></asp:Label>
</ItemTemplate>
</asp:DataList>

.cs page

private void BindGrid()
{
string sql = "Select * from Country Order By Country_Name";
SqlDataAdapter da = new SqlDataAdapter(sql, “Yourconnectionstring”);
DataTable dt = new DataTable();
da.Fill(dt);

dlMyCountry.DataSource = dt;
dlMyCountry.DataBind();
}

protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindGrid();
}
}

try this code and let me know.

  Vickey F replied to Badri
09-Aug-11 04:48 AM

GridView - GridView displays the values of a data source in a table where each column represents a field and each row represents a record. The GridView control enables you to select, sort, and edit these items.

It is Data Control in ASP.NET, means it provides you to edit, update and delete record using its inbuilt
functionality.

for example follow these links-
http://msdn.microsoft.com/en-us/library/aa479353.aspx
and
http://www.c-sharpcorner.com/UploadFile/raj1979/GridViewExamplesForASPNET2009162008055815AM/GridViewExamplesForASPNET20.aspx

I hope this will help you.
 

Create New Account
help
textboxes in footer row of GridView using ItemTemplate and FooterTemaplete. protected void GridView1_RowCommand ( object sender, GridViewCommandEventArgs e) { if (e.CommandName = = "Add" ) { string strFirstName = ((TextBox) GridView1.FooterRow.FindControl( "txtFname" )).Text; string strLastName Text; string strLocation = ((TextBox)GridView1.FooterRow. FindControl( "txtLoc" )).Text; / / SqlDataSource1.InsertParameters.Clear(); / / SqlDataSource1.InsertParameters.Add / / ("FirstName", strFirstName); / / SqlDataSource1.InsertParameters.Add / / ("LastName", strLastName); / / SqlDataSource1.InsertParameters.Add / / ("Department", strDepartment); / / SqlDataSource1.InsertParameters.Add / / ("Location", strLocation); SqlDataSource1.InsertParameters[ "FirstName" ].DefaultValue = strFirstName; SqlDataSource1.InsertParameters[ "LastName" ].DefaultValue = strLastName; SqlDataSource1.InsertParameters[ "Department" ].DefaultValue = strDepartment; SqlDataSource1.InsertParameters[ "Location" ].DefaultValue = strLocation; SqlDataSource1.Insert(); } } refer in footer row of GridView using ItemTemplate and FooterTemaplete. Go to design view of aspx page and drag a GridView control from toolbox, click on smart tag of GridView and choose Enable Editing , enable deleting checkbox in gridView smart tag Now go to html source of page and define DatakeyNames field in gridview source < asp:GridView ID = "GridView1" runat = "server" AutoGenerateColumns = "False boundFields and put ItemTemplate and EditItemTemplate and labels and textboxs respectively, complete html source of page should look like this < form id = "form1" runat = "server" > < div > < asp:GridView ID = "GridView1" runat
new row when user clicks on add button.in my grid view i have one dropdownlist please tell me how to do this task. . . . . with out using datasource hi this code sc = new SqlConnection(ConfigurationManager.ConnectionStrings["Pubs"].ToString()); SqlCommand sm = new SqlCommand("Select * from table1", sc); SqlDataAdapter sa = new SqlDataAdapter(sm); sa.Fill(dt); if (!IsPostBack) { this.GridView2.DataSource = dt.DefaultView; this.GridView2.DataBind(); } } protected Customers_RowCommand" > <Columns> <asp:TemplateField HeaderText = "CustomerId" > <ItemTemplate> <%# Eval( "CustomerId" ) %> < / ItemTemplate> < / asp:TemplateField> <asp:TemplateField HeaderText = "FirstName" > <ItemTemplate> <%# Eval( "FirstName" ) %> < / ItemTemplate> <EditItemTemplate> <asp:TextBox runat = "server" ID = "EditFirstName" Text = '' <%# Bind( "FirstName" ) %> ' / > < / EditItemTemplate> <FooterTemplate> <asp:TextBox runat = "server" ID = "InsertFirstName" Text = '' <%# Bind( "FirstName" ) %> ' / > < / FooterTemplate> < / asp:TemplateField> <asp:TemplateField HeaderText LastName" > <ItemTemplate> <%# Eval( "LastName" ) %> < / ItemTemplate> <EditItemTemplate> <asp:TextBox runat = "server" ID = "EditLastName" Text = '' <%# Bind( "LastName" ) %> ' / > < / EditItemTemplate
insert how to insert in gridview hi, here is the code for you on .aspx page < tr > < td width = "100" align = "right" bgcolor = "#eeeeee" class = "header1" > Employee Data Using the GridView FFFFFF" > < asp:GridView ID = "gvwExample" runat = "server" AutoGenerateColumns = "False" CssClass = "basix" > < columns > < asp:BoundField DataField = "firstname" HeaderText = "First Name" / > < asp:BoundField DataField = "lastname" HeaderText = "Last Name" / > < asp:BoundField DataField = "hiredate" HeaderText = "Date Hired" / > < / columns > < / asp:GridView > < asp:label ID = "lblStatus" runat = "server" > < / asp:label > < / td > < / tr > on .aspx.cs page using System; using System.Data; using System.Configuration; using System.Web; using System.Web.Security System.Web.UI.HtmlControls; using System.Data.SqlClient; public partial class _Default : System.Web.UI.Page { protected void Page_Load( object sender, EventArgs e) { SqlCommand cmd = new SqlCommand( "SELECT firstname, lastname, hiredate FROM EMPLOYEES" , new SqlConnection( "Server = localhost;Database = Northwind;Trusted_Connection = True;" )); try { cmd.Connection.Open string " ConnString" 3. create a aspx file and copy paste the code to your file <% @ Page Language = "C#" ClassName = "Default_aspx" %> <! DOCTYPE html PUBLIC "- / / W3C / / DTD XHTML 1.1 / / EN" "http: / / www
this code = protected void GetDetails_Click(object sender, EventArgs e) { SqlConnection con = new SqlConnection("con string "); SqlDataAdapter da; string mySQL = "SELECT * FROM emptable "; da = new SqlDataAdapter(mySQL, con); con.Open(); DataSet ds = new DataSet(); da.Fill(ds); if(ds.Tables[0 MyDatabase;Integrated Security = SSPI" ; string qry = @ "select * from employee" ; SqlConnection conn = new SqlConnection ( connString ) ; try { SqlDataAdapter da = new SqlDataAdapter () ; da.SelectCommand = new SqlCommand ( qry, conn ) ; SqlCommandBuilder cb = new SqlCommandBuilder ( da ) ; DataSet ds = new DataSet ds, "employee" ) ; DataTable dt = ds.Tables [ "employee" ] ; / / Add a row DataRow newRow = dt.NewRow () ; newRow [ "firstname" ] = "y" ; newRow [ "lastname" ] = "y" ; dt.Rows.Add ( newRow ) ; foreach ( DataRow row in dt.Rows ){ Console.WriteLine ( "{0} {1}" , row [ "firstname" ] .ToString () .PadRight ( 15 ) , row [ "lastname" ] .ToString () .PadLeft ( 25 )) ; } da.Update(ds, "employee"); / / required method } catch ( Exception e ) { Console.WriteLine ( "Error