Written on 10:26 PM by Mj blog
Let’s see how to merge the Header in the Gridview this can be achieved by either C# . Lets place a gridview on the aspx HTML source file
Sample View
HTML Source Code
<asp:GridView ID="GridView1" runat="server" BackColor="White"
BorderColor="#CCCCCC" BorderStyle="None" BorderWidth="1px" CellPadding="4"
ForeColor="Black" GridLines="Horizontal" onrowcreated="GridView1_RowCreated">
<FooterStyle BackColor="#CCCC99" ForeColor="Black" />
<PagerStyle BackColor="White" ForeColor="Black" HorizontalAlign="Right" />
<SelectedRowStyle BackColor="#CC3333" Font-Bold="True" ForeColor="White" />
<HeaderStyle BackColor="#333333" Font-Bold="True" ForeColor="White"
BorderColor="#000066" BorderStyle="Solid" BorderWidth="1px" />
</asp:GridView>
C# Code
It’s simple create row created event and use this code
protected void GridView1_RowCreated(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.Header)
{
//Build Gridview in runtime
GridView objGrdView = (GridView)sender;
GridViewRow objGrdViewRow = new
GridViewRow(0, 0, DataControlRowType.Header, DataControlRowState.Insert);
//Create table cell
TableCell objTblCell = new TableCell();
//Add cell
objTblCell.Text = "Name"; //provide the heard test
objTblCell.ColumnSpan = 2;
objTblCell.CssClass = "lblColor";
objTblCell.HorizontalAlign = HorizontalAlign.Center;
objGrdViewRow.Cells.Add(objTblCell);
//Add cell
objTblCell = new TableCell(); //Create another cell
objTblCell.HorizontalAlign = HorizontalAlign.Center;
objTblCell.CssClass = "lblColor";
objTblCell.Text = "Employee";
objTblCell.ColumnSpan = 1;
objGrdViewRow.Cells.Add(objTblCell);
objGrdView.Controls[0].Controls.AddAt(0, objGrdViewRow);
}
}
we have checked for the row type whether its a header row and then we have taken the instance of the gridview then we have created new gridview row which is like tr of the table and table cell which is equal to the td of the table and we have inserted those td in the tr and then inserted the row on the first row of the gridview (which is nothing but a table on the runtime)
I forgot to say guys you have to bind the gridview ….
Hope its useful
Posted in
Gridview
|
Written on 3:30 PM by Mj blog
Let's see how to insert a row in gridview from its footer template, Normally we will have seperate div area where we keep our Label and texbox and dropdownlist seperately and we will have a add button lets now reduce the space constraint by providing those controls on the footer template of the gridview and save space, we also know that by default gridview does not supports inserting data but now we are going to override that rule
Issues and work around
Before doing this there is special case when the database has no records the gridview never appears rite what shall we do this problem for this i have given a solution in my last blog check it . I am adding that source code also with this blog
Our Scenario
In this scenario I am going to have three columns one is ID column which will not be inserted and secound is Name which needs to be inserted hence we place a textbox and there is Status selection hence we are keeping a dropdownlist in the footer control then create a template for insert button
Now the steps to be followed
Step 1: Place a gridview and bind it with the database, create columns in the gridview and convert that to template
Step 2: Place Footer template for each column that to be inserted and create the controls we need for inserting the row
step 3 : Here we are going to bind our dropdownlist , to do so create gridview rowcreated event and bind the dropdownlist
Step 4: Then create a onclick event for insert button , provide the CommandName="Insert" and write the code for inserting the records in database
Let's see the HTML Source code
<asp:GridView
ID="GridView1"
runat="server"
AutoGenerateColumns="False" DataKeyNames="Id" CellPadding="4" ForeColor="Black" GridLines="Vertical" ShowFooter="True" BackColor="White"
BorderColor="#DEDFDE" BorderStyle="Solid"
BorderWidth="2px" OnRowCreated="GridView1_RowCreated">
<RowStyle BackColor="#F7F7DE" />
<Columns>
<asp:TemplateField HeaderText="ID" InsertVisible="False" SortExpression="ID">
<EditItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%# Eval("ID") %>'></asp:Label>
</EditItemTemplate>
<ItemTemplate> <asp:Label ID="Label1" runat="server" Text='<%# Bind("ID") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Name" SortExpression="Name">
<EditItemTemplate>
<asp:TextBox ID="TextBox1" runat="server" Text='<%# Bind("Name") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label2" runat="server" Text='<%# Bind("Name") %>'></asp:Label>
</ItemTemplate>
<FooterTemplate>
<asp:TextBox ID="TextBox4" runat="server"></asp:TextBox>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="isactive">
<EditItemTemplate>
<asp:TextBox ID="TextBox2" runat="server" Text='<%# Bind("isactive") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label3" runat="server" Text='<%# Bind("isactive") %>'></asp:Label> </ItemTemplate>
<FooterTemplate>
<asp:DropDownList ID="ddlIsActive" runat="server">
</asp:DropDownList>
</FooterTemplate> </asp:TemplateField>
<asp:TemplateField FooterStyle-HorizontalAlign="Center">
<FooterTemplate>
<asp:Button ID="btnInsert" runat="server" Text="Insert" CommandName="Insert" OnClick="InsertRows" />
</FooterTemplate>
</asp:TemplateField>
</Columns>
<FooterStyle BackColor="#CCCC99" />
<PagerStyle BackColor="#F7F7DE" ForeColor="Black" HorizontalAlign="Right" />
<EmptyDataTemplate>
No Record Found
</EmptyDataTemplate>
<SelectedRowStyle BackColor="#CE5D5A" Font-Bold="True" ForeColor="White" />
<HeaderStyle BackColor="#6B696B" Font-Bold="True" ForeColor="White" />
<AlternatingRowStyle BackColor="White" />
</asp:GridView>
Lets See the C# Code
using System;
using System.Collections.Generic;
using System.Collections;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Xml;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
public partial class _Default : System.Web.UI.Page {
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack) {
BindGrid(); //Binding the gridview on page load
}
}
/// <summary>
/// This method connect to Sql database, fetch data returns dataset
/// </summary>
/// <returns></returns>
public DataSet ReturnMenuDetails()
{
DataSet ds = new DataSet();
using (SqlConnection sqlconn = new SqlConnection(ConfigurationManager.ConnectionStrings ["SqlConnectionString"].ConnectionString.ToString()))
{
sqlconn.Open();
SqlDataAdapter sqldap = new
SqlDataAdapter("select ID , Name , isactive from detail", sqlconn); sqldap.Fill(ds);
}
return ds;
}
/// <summary>
/// This method return a datatable with empty row
/// </summary>
/// <returns></returns>
public DataTable ReturnEmptyDataTable()
{
DataTable dtMenu = new DataTable(); //declaringa datatable
DataColumn dcMenuID = new DataColumn("ID", typeof(System.Int32));
//creating a column in the same
//Name of column available in the sql server
dtMenu.Columns.Add(dcMenuID);// Adding column to the datatable
DataColumn dcMenuName = new
DataColumn("Name", typeof(System.String));
dtMenu.Columns.Add(dcMenuName);
DataColumn dcMenuActive = new
DataColumn("isactive", typeof(System.String));
dtMenu.Columns.Add(dcMenuActive);
DataRow datatRow = dtMenu.NewRow();
//Inserting a new row,datatable .newrow creates a blank row
dtMenu.Rows.Add(datatRow);//adding row to the datatable
return dtMenu;
}
/// <summary>
/// This method checks for no of rows returned from sql server and binds the
/// datasource with the gridview based on the resultset, if no rows returned are zero
/// from sql server then it will bind the datatable to the gridview to display the columns
/// when no record was returned
/// </summary>
public void BindGrid()
{
if (ReturnMenuDetails().Tables[0].Rows.Count > 0)
{
GridView1.DataSource = ReturnMenuDetails();
}
else {
GridView1.DataSource = ReturnEmptyDataTable();
}
GridView1.DataBind();
}
/// <summary>
/// This method will search the dropdownlist in the footer template of the gridview
/// and bind the dropdownlist for this example i have used arraylist
/// we can bind from database also
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void GridView1_RowCreated(object sender, GridViewRowEventArgs e)
{
//Checking whether the rended row is footer
if (e.Row.RowType == DataControlRowType.Footer)
{
ArrayList arraDropdown = new ArrayList();
arraDropdown.Add(new ListItem("Select", "-1"));
arraDropdown.Add(new ListItem("Yes", "Yes"));
arraDropdown.Add(new ListItem("No", "No"));
//searching for dropdownlist in the footer view of gridview
DropDownList ddl = (DropDownList)e.Row.Cells[0].FindControl("ddlIsActive");
//Binding the dropdownlist with arraylist
ddl.DataSource = arraDropdown;
ddl.DataBind();
}
}
/// <summary>
/// This method will be fired when ever the insert button is clicked
/// This method searches for the textbox and dropdownlist placed in
/// the footer template of gridview and passes the values to the
/// SQL query and binds the grid
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void InsertRows(object sender, EventArgs e)
{
TextBox txtName = (TextBox)GridView1.FooterRow.FindControl("TextBox4");
DropDownList ddlys = (DropDownList)GridView1.FooterRow.FindControl("ddlIsActive");
using (SqlConnection sqlconn = new SqlConnection(ConfigurationManager.ConnectionStrings ["SqlConnectionString"].ConnectionString.ToString()))
{
SqlCommand sqldap = new
SqlCommand("insert into switch_master(switch_Name,isactive,created_by) values ('" + txtName.Text + "','" + ddlys.SelectedItem.Text + "','Manoj')", sqlconn);
sqlconn.Open();
sqldap.ExecuteNonQuery();
}
BindGrid();
}
}
Thus we can insert new rows in the within gridview
Posted in
Gridview
|
Written on 3:21 PM by Mj blog
Lets see how to show columns in empty gridview and also show header and footer of empty gridview. The gridview does not show any header or footer when the datasource returns a empty data the only thing we can do is give some message in the empty data template, but we can acheive this following way
Step 1: place a gridview on the aspx page
Step 2: Set ShowHeader and ShowFooter option as true in the gridview property
Step 3: Bind the gridview with dataset
Step 4: create a datatable having the same column name and no. of columns of database counter part
Step 5: when binding check whether gridview with datasource check for the no. of rows the dataset returns from the databse,if the rows not greater than zero bind the datatable to the gridview
Step 6: This will show the header, footer and column also
Now See the Sample code …..
Default.aspx HTML Source code
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
DataKeyNames="Id" CellPadding="4" ForeColor="#333333" GridLines="None" ShowFooter="True" >
<RowStyle BackColor="#F7F6F3"ForeColor="#333333" />
<Columns>
<asp:BoundField DataField="ID" HeaderText="ID" InsertVisible="False" ReadOnly="True" SortExpression="ID" />
<asp:BoundField DataField="Name" HeaderText="Name" SortExpression="Name" />
</Columns>
<FooterStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="#284775" ForeColor="White" HorizontalAlign="Center" />
<EmptyDataTemplate>
No Record Found
</EmptyDataTemplate>
<SelectedRowStyle BackColor="#E2DED6" Font-Bold="True" ForeColor="#333333" />
<HeaderStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
<EditRowStyle BackColor="#999999" />
<AlternatingRowStyle BackColor="White" ForeColor="#284775" />
</asp:GridView>
The Gridview has two columns in the with column name as ID and Name, show footer and show header option is set to true
Default.aspx.cs C# source code
using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Xml;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
public partial class _Default : System.Web.UI.Page {
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindGrid(); //Binding the gridview on page load
}
}
/// <summary>
/// This method connect to Sql database, fetch data returns dataset
/// </summary>
/// <returns></returns>
public DataSet ReturnMenuDetails()
{
DataSet ds = new DataSet();
using (SqlConnection sqlconn = new SqlConnection(ConfigurationManager.ConnectionStrings["SqlConnectionString"].ConnectionString.ToString()))
{
SqlDataAdapter sqldap = new
SqlDataAdapter("select * from details", sqlconn);
sqldap.Fill(ds);
}
return ds;
}
/// <summary>
/// This method return a datatable with empty row
/// </summary>
/// <returns></returns>
public DataTable ReturnEmptyDataTable()
{
DataTable dtMenu = new DataTable(); //declaringa datatable
DataColumn dcMenuID = new DataColumn("ID", typeof(System.Int32));
//creating a column in the same
//Name of column available in the sql server
dtMenu.Columns.Add(dcMenuID);// Adding column to the datatable
DataColumn dcMenuName = new DataColumn("Name", typeof(System.String));
dtMenu.Columns.Add(dcMenuName);
DataRow datatRow = dtMenu.NewRow();
//Inserting a new row,datatable .newrow creates a blank row
dtMenu.Rows.Add(datatRow);//adding row to the datatable
return dtMenu;
}
/// <summary>
/// This method checks for no of rows returned from sql server and binds the
/// datasource with the gridview based on the resultset, if no rows returned are zero
/// from sql server then it will bind the datatable to the gridview to display the columns
/// when no record was returned
/// </summary>
public void BindGrid()
{
//checking for no. of rows returned from the dataset
if(ReturnMenuDetails().Tables[0].Rows.Count>0)
{
GridView1.DataSource = ReturnMenuDetails();
}
else
{
GridView1.DataSource = ReturnEmptyDataTable();
}
GridView1.DataBind();
}
}
Thus we can show the header, footer and the column name
Posted in
Gridview
|
Written on 9:57 PM by Mj blog
As a web developer i frequently use gridview to show some of reports where I checkbox for users to select the records for particular transactions like exporting to excel or printing the rows. So lets do that in GMAIL , ORKUT style giving a command
"Select : All None" style....
Even though we keep checkboxes in the gridview and give a name say "checkbox1" it will dynamically create its own name in the runtime so to check the name we first do the following steps
Step 1 : Keep the GridView in the design view
Step 2 : Bind the datasource of ur wish (please dont mix up UI and data layer )
Step 3: Now make the column in which the check box will be placed usually the column which we keep as datakeys as for I have worked.
Step 4 : After binding the GridView with data source convert the data keys column into template and click the "Edit Template "
Step 5 : In the ItemTemplate delete the Label control and place the checkbox and bind the datamember the syntax as follows
<asp:TemplateField HeaderText="userid" SortExpression="userid">
<EditItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%# Eval("userid") %>'></asp:Label>
</EditItemTemplate>
<ItemTemplate>
<asp:CheckBox ID="CheckBox1" runat="server" Text='<%# Eval("userid") %>/>
</ItemTemplate>
</asp:TemplateField>
Now we have placed the Check box now we will check what name it creates in the runtime
Step 6 : Press CTRL + F5 and the web page will be loaded now right click on the page and select " View Source " . it will automatically open the notepad with the HTML tags in it to search for the checkbox with its name "CheckBox1" you will get the name as "GridView1_ctl02_CheckBox1", "GridView1_ctl03_CheckBox1", GridView1_ctl04_CheckBox1.... etc
if you are using Master Page and you add the GridView in the Content page then the name will be different its like ct_100.... something .
So the Checkbox name is different hence its very difficult to give specific name in the javascript code but fortunately we have "CheckBox1" as common in all the checkbox generated in the gridview with this we can build the javascript code.
JavaScript code to select All and None Checkboxs in Gridview
Algorithm
Step 1 : Read all the controls in the generated web page
Step 2 : Search for the control type checkbox in the web page
Step 3 : Search for the control name consisting of the word "CheckBox1"
Step 4 : Give the status of True or False
JavaScript Code
// funtion for checking all the checkbox only in gridview
function checkAll()
{
//find the total controls in the web page
for (var i = 0; i < document.form1.elements.length; i++)
{
//Assign it to an array
var e = document.form1.elements[i];
//search for the control type checkbox
if ( (e.type == 'checkbox'))
{
//Search for the checkbox with the name containing "CheckBox1"
if(e.name.indexOf('CheckBox1')!=-1)
{
e.checked = true; //Status of the checkbox
}
}
}
}
// funtion for unchecking all the checkbox only in gridview
function uncheckAll()
{
//find the total controls in the web page
for (var i = 0; i < document.form1.elements.length; i++)
{
//Assign it to an array
var e = document.form1.elements[i];
//search for the control type checkbox
if ( (e.type == 'checkbox'))
{
//Search for the checkbox with the name containing "CheckBox1"
if(e.name.indexOf('CheckBox1')!=-1)
{
e.checked = false; //Status of the checkbox
}
}
}
}
HTML Code
<body>
<form id="form1" runat="server">
select : <a href ="javascript:checkAll()">All</a> <a href="javascript:uncheckAll();">None</a>
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataKeyNames="userid" DataSourceID="SqlDataSource1">
<Columns>
<asp:TemplateField HeaderText="userid" SortExpression="userid">
<EditItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%# Eval("userid") %>'></asp:Label>
</EditItemTemplate>
<ItemTemplate>
<asp:CheckBox ID="CheckBox1" runat="server" Text='<%# Eval("userid") %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="username" HeaderText="username" SortExpression="username" />
<asp:BoundField DataField="Dob" HeaderText="Dob" SortExpression="Dob" />
<asp:BoundField DataField="gender" HeaderText="gender" SortExpression="gender" />
<asp:BoundField DataField="Address1" HeaderText="Address1" SortExpression="Address1" />
<asp:BoundField DataField="Address2" HeaderText="Address2" SortExpression="Address2" />
<asp:BoundField DataField="Address3" HeaderText="Address3" SortExpression="Address3" />
<asp:BoundField DataField="city" HeaderText="city" SortExpression="city" />
<asp:BoundField DataField="State" HeaderText="State" SortExpression="State" />
<asp:BoundField DataField="Country" HeaderText="Country" SortExpression="Country" />
</Columns>
</asp:GridView>
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:DBConnectionString %>"
SelectCommand="SELECT [userid], [username], [Dob], [gender], [Address1], [Address2], [Address3], [city], [State], [Country] FROM [User_Master]">
</asp:SqlDataSource>
</form>
</body>
Thus we can select the checkboxes kept inside the gridview and gridview only.
Posted in
Gridview
|