IT Community - Software Programming, Web Development and Technical Support

C#.Net, ASP.Net Data Grid Frequently Asked Questions

This is a discussion on C#.Net, ASP.Net Data Grid Frequently Asked Questions within the C# Programming forums, part of the Software Development category; Hi All, Here is the space to discuss about data grid using ASP.Net , C#. Net in Web development and ...


Go Back   IT Community - Software Programming, Web Development and Technical Support > Software Development > C# Programming

Register FAQ Members List Calendar Mark Forums Read
  #1 (permalink)  
Old 12-26-2007, 04:03 AM
a.deeban a.deeban is offline
D-Web Analyst
 
Join Date: May 2007
Posts: 279
a.deeban is on a distinguished road
Default C#.Net, ASP.Net Data Grid Frequently Asked Questions

Hi All,

Here is the space to discuss about data grid using ASP.Net , C#. Net in Web development and Windows application.


thanks..


A. Deeban.
Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
Sponsored Links
  #2 (permalink)  
Old 12-26-2007, 04:14 AM
Sathish Kumar Sathish Kumar is offline
D-Web Analyst
 
Join Date: Feb 2007
Posts: 304
Sathish Kumar is on a distinguished road
Exclamation How can I programatically set the rowheight of a row in my DataGrid?

Hi,
How can I programatically set the rowheight of a row in my DataGrid?
__________________
Sathish Kumar.R
Knowledge is meant to SHARE
Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #3 (permalink)  
Old 12-26-2007, 04:15 AM
a.deeban a.deeban is offline
D-Web Analyst
 
Join Date: May 2007
Posts: 279
a.deeban is on a distinguished road
Default Re: C#.Net, ASP.Net Data Grid Frequently Asked Questions

Hi sathish...


Here is a solution . It uses reflection to access the protected DataGridRows collection so he can set the row height.


public void AutoSizeGrid()

{

// DataGrid should be bound to a DataTable for this part to

// work.

int numRows = ((DataTable)gridTasks.DataSource).Rows.Count;

Graphics g = Graphics.FromHwnd(gridTasks.Handle);

StringFormat sf = new StringFormat(StringFormat.GenericTypographic);

SizeF size;



// Since DataGridRows[] is not exposed directly by the DataGrid

// we use reflection to hack internally to it.. There is actually

// a method get_DataGridRows that returns the collection of rows

// that is what we are doing here, and casting it to a System.Array

MethodInfo mi = gridTasks.GetType().GetMethod("get_DataGridRows",

BindingFlags.FlattenHierarchy | BindingFlags.IgnoreCase | BindingFlags.Instance

| BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Static);



System.Array dgra = (System.Array)mi.Invoke(gridTasks,null);



// Convert this to an ArrayList, little bit easier to deal with

// that way, plus we can strip out the newrow row.

ArrayList DataGridRows = new ArrayList();

foreach (object dgrr in dgra)

{

if (dgrr.ToString().EndsWith("DataGridRelationshipRow ")==true)

DataGridRows.Add(dgrr);

}



// Now loop through all the rows in the grid

for (int i = 0; i < numRows; ++i)

{

// Here we are telling it that the column width is set to

// 400.. so size will contain the Height it needs to be.

size = g.MeasureString(gridTasks[i,1].ToString(),gridTasks.Font,400,sf);

int h = Convert.ToInt32(size.Height);

// Little extra cellpadding space

h = h + 8;



// Now we pick that row out of the DataGridRows[] Array

// that we have and set it's Height property to what we

// think it should be.

PropertyInfo pi = DataGridRows[i].GetType().GetProperty("Height");

pi.SetValue(DataGridRows[i],h,null);



// I have read here that after you set the Height in this manner that you should

// Call the DataGrid Invalidate() method, but I haven't seen any prob with not calling it..



}



g.Dispose();

}



Thannx...
Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #4 (permalink)  
Old 12-26-2007, 05:18 AM
KiruthikaSambandam KiruthikaSambandam is offline
D-Web Analyst
 
Join Date: Aug 2007
Posts: 332
KiruthikaSambandam is on a distinguished road
Default Re: C#.Net, ASP.Net Data Grid Frequently Asked Questions

Hi,
What’s the difference between the System.Web.UI.WebControls.DataGrid and and System.Windows.Forms.DataGrid?


ThankQ
Kirthika
Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #5 (permalink)  
Old 12-26-2007, 06:26 AM
SaravananJ SaravananJ is offline
D-Web Programmer
 
Join Date: Aug 2007
Posts: 79
SaravananJ is on a distinguished road
Default Re: C#.Net, ASP.Net Data Grid Frequently Asked Questions

Hi Kirthika,

The first one System.Web.UI.WebControls.DataGrid is the DataGrid control used in developing web application and the second one System.Windows.Forms.DataGrid is meant for Windows application programming.

Note: All the controls which comes under System.Web namespace is meant for developing web application and the controls which comes under System.Windows namespace is meant for Windows application development
__________________
J.Saravanan
Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #6 (permalink)  
Old 12-26-2007, 10:16 PM
Mramesh Mramesh is offline
D-Web Sr.Programmer
 
Join Date: Sep 2007
Location: Chennai
Posts: 106
Mramesh is on a distinguished road
Send a message via MSN to Mramesh
Question Re: C#.Net, ASP.Net Data Grid Frequently Asked Questions

Hi all,

Can Anybody tell me how to remove the duplicate rows in a dataset please. If possible give me sample code.

Thanx in Advance...

M. Ramesh kumar
Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #7 (permalink)  
Old 12-26-2007, 10:28 PM
Sundaram Sundaram is offline
D-Web Sr.Programmer
 
Join Date: Mar 2007
Location: chennai
Posts: 117
Sundaram is on a distinguished road
Send a message via MSN to Sundaram Send a message via Yahoo to Sundaram
Default Re: C#.Net, ASP.Net Data Grid Frequently Asked Questions

Hi Ramesh,

This method will remove the duplicate rows from a datatable, based on a column. Pass to the method the datatable and the column to be checked for duplicate values.

Call the method like this :

Code:
RemoveDuplicateRows(dT,"ID");
This is the implementation.

Code:
public void RemoveDuplicateRows(DataTable dTable,string colName)
{
        Hashtable hTable = new Hashtable();
        ArrayList duplicateList = new ArrayList();

        foreach(DataRow drow in dTable.Rows)
        {
                try
                {
                            hTable.Add(drow[colName],string.Empty);
                }
                catch
                {
                        duplicateList.Add(drow); 
                }
         }

          foreach(DataRow dRow in duplicateList)
                   dTable.Rows.Remove(dRow);
}
Cheers !
Sundaram
Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #8 (permalink)  
Old 12-26-2007, 10:38 PM
Sathish Kumar Sathish Kumar is offline
D-Web Analyst
 
Join Date: Feb 2007
Posts: 304
Sathish Kumar is on a distinguished road
Post Re: C#.Net, ASP.Net Data Grid Frequently Asked Questions

hi all,

copy past this code and make change with ur app path etc...
Code:
 cmd.CommandText = "delete from emp where id not in (select min(id) from emp group by name,address)"
       cmd.ExecuteNonQuery()
       da.SelectCommand = cmd
       da.Fill(ds, "emp")
       DataGrid1.DataSource = ds.Tables("emp")
       DataGrid1.SetDataBinding(ds, "emp")
       DataGrid1.Refresh()
Regards,

SathisKumar R
__________________
Sathish Kumar.R
Knowledge is meant to SHARE

Last edited by Sathish Kumar : 12-27-2007 at 11:54 PM.
Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #9 (permalink)  
Old 12-27-2007, 11:55 PM
Sathish Kumar Sathish Kumar is offline
D-Web Analyst
 
Join Date: Feb 2007
Posts: 304
Sathish Kumar is on a distinguished road
Exclamation Re: C#.Net, ASP.Net Data Grid Frequently Asked Questions

Hi guys,
I must add custom ColumnStyles to the designer so I can use them in a DataGrid at design time.Can anybody tell me how to do this?
__________________
Sathish Kumar.R
Knowledge is meant to SHARE
Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #10 (permalink)  
Old 12-27-2007, 11:58 PM
a.deeban a.deeban is offline
D-Web Analyst
 
Join Date: May 2007
Posts: 279
a.deeban is on a distinguished road
Default Re: C#.Net, ASP.Net Data Grid Frequently Asked Questions

Hi sathish...


To use custom ColumnStyles in the designer, you need to do three things.

1) Derive a CustomColumnStyle to implement the functionality you want.

2) Derive a DataGridTableStyle class and add a new GridColumnStyles property that uses this derived CollectionEditor. This GridColumnStyle hides the base class member.

3) Derive a DataGrid and add a new TableStyles collection that uses your derived table style.

Both steps 2 and 3 will require you to derive a CollectionEditor and override CreateNewItemTypes to use the derived classes from each step in the designer.


Thnx...
Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #11 (permalink)  
Old 12-28-2007, 12:02 AM
Sathish Kumar Sathish Kumar is offline
D-Web Analyst
 
Join Date: Feb 2007
Posts: 304
Sathish Kumar is on a distinguished road
Exclamation Re: C#.Net, ASP.Net Data Grid Frequently Asked Questions

Hi,
I am losing the settings on a DataGrid set during design-time.Do anybody know why this happens?
__________________
Sathish Kumar.R
Knowledge is meant to SHARE
Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #12 (permalink)  
Old 12-28-2007, 12:04 AM
a.deeban a.deeban is offline
D-Web Analyst
 
Join Date: May 2007
Posts: 279
a.deeban is on a distinguished road
Default Re: C#.Net, ASP.Net Data Grid Frequently Asked Questions

Hi Sathish...


This is possible if you assign a custom DataGridTableStyle to the DataGrid. The properties in the DataGridTableStyle will then replace certain properties in the DataGrid. Take a look at DataGrid class reference for a list of these properties.


Thnx..
Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #13 (permalink)  
Old 12-28-2007, 01:37 AM
shaalini shaalini is offline
D-Web Analyst
 
Join Date: Apr 2007
Posts: 342
shaalini is on a distinguished road
Default Re: C#.Net, ASP.Net Data Grid Frequently Asked Questions

hi,
How to add a new row in the datagrid when each time add button is clicked
__________________
Shaalini.S
Be the Best of Whatever you are...
Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #14 (permalink)  
Old 01-02-2008, 09:54 PM
a.deeban a.deeban is offline
D-Web Analyst
 
Join Date: May 2007
Posts: 279
a.deeban is on a distinguished road
Default Re: C#.Net, ASP.Net Data Grid Frequently Asked Questions

Hi..

The important thing to know about your question is that you can't add a row to a datagrid, you must add a row to the datasource for the grid then re-bind the grid.

Usually, the datasource for the grid is some class that has a item count property. From that you can determine the last item index, then add 1, set the EditItemIndex of the grid to that value and re-bind the grid. Now you have a "new row" in the grid that is set up for data entry. Then you just need to modify your logic a bit to do a data insert instead of an update. When you save the row.

Hope this will help you...
Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #15 (permalink)  
Old 01-02-2008, 10:06 PM
a.deeban a.deeban is offline
D-Web Analyst
 
Join Date: May 2007
Posts: 279
a.deeban is on a distinguished road
Default Re: C#.Net, ASP.Net Data Grid Frequently Asked Questions

Hi...

Here is the sample source code...


ASP. Net Source

Code:
<%@ Page language="c#" Codebehind="WebForm1.aspx.cs" AutoEventWireup="false" Inherits="TestDGrid.WebForm1" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" >
<HTML>
	<HEAD>
		<title>WebForm1</title>
		<meta name="GENERATOR" Content="Microsoft Visual Studio .NET 7.1">
		<meta name="CODE_LANGUAGE" Content="C#">
		<meta name="vs_defaultClientScript" content="JavaScript">
		<meta name="vs_targetSchema" content="http://schemas.microsoft.com/intellisense/ie5">
	</HEAD>
	<body MS_POSITIONING="GridLayout">
		<form id="Form1" method="post" runat="server">
			<asp:DataGrid id="DataGrid1" style="Z-INDEX: 101; LEFT: 112px; POSITION: absolute; TOP: 16px"
				runat="server" AutoGenerateColumns="False">
				<Columns>
					<asp:TemplateColumn HeaderText="Id">
						<ItemTemplate>
							<asp:TextBox id="txtID" runat="server" Text='<%# DataBinder.Eval(Container.DataItem, "iEid ") %>'>
							</asp:TextBox>
						</ItemTemplate>
					</asp:TemplateColumn>
					<asp:TemplateColumn HeaderText="Name">
						<ItemTemplate>
							<asp:TextBox id="txtName" runat="server" Text='<%# DataBinder.Eval(Container.DataItem, "cEName") %>'>
							</asp:TextBox>
						</ItemTemplate>
					</asp:TemplateColumn>
					<asp:TemplateColumn HeaderText="Salary">
						<ItemTemplate>
							<asp:TextBox id="txtSal" runat="server" Text='<%# DataBinder.Eval(Container.DataItem, "dSalary") %>'>
							</asp:TextBox>
						</ItemTemplate>
					</asp:TemplateColumn>
				</Columns>
			</asp:DataGrid>
			<asp:Button id="btAdd" style="Z-INDEX: 102; LEFT: 64px; POSITION: absolute; TOP: 24px" runat="server"
				Text="Add"></asp:Button>
		</form>
	</body>
</HTML>
C# Source:

Code:
using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;
namespace TestDGrid
{
	/// <summary>
	/// Summary description for WebForm1.
	/// </summary>
	
	public class WebForm1 : System.Web.UI.Page
	{
		protected System.Web.UI.WebControls.DataGrid DataGrid1;
		protected DataTable table = new DataTable();
		protected System.Web.UI.WebControls.Button btAdd;
		SqlConnection con = new SqlConnection(@"Server=Servername;DataBase=database name;uid=sa;pwd=sa;");
	
		private void Page_Load(object sender, System.EventArgs e)
		{
			// Put user code to initialize the page here
			if(!IsPostBack)
			{   fill();
				BindDG();
			}
		}

		public void fill()
		{
			SqlDataAdapter da = new SqlDataAdapter("Select * from emp",con);
			DataSet ds = new DataSet();
			da.Fill(table);
			
		}

		public void BindDG()
		{
			DataGrid1.DataSource=table;
			DataGrid1.DataBind();
		}

		public void Nrow()
		{
			table.Rows.InsertAt(table.NewRow(),0);
			
		}

		#region Web Form Designer generated code
		override protected void OnInit(EventArgs e)
		{
			//
			// CODEGEN: This call is required by the ASP.NET Web Form Designer.
			//
			InitializeComponent();
			base.OnInit(e);
		}
		
		/// <summary>
		/// Required method for Designer support - do not modify
		/// the contents of this method with the code editor.
		/// </summary>
		private void InitializeComponent()
		{    
			this.btAdd.Click += new System.EventHandler(this.btAdd_Click);
			this.Load += new System.EventHandler(this.Page_Load);

		}
		#endregion

		private void btAdd_Click(object sender, System.EventArgs e)
		{
		DataGrid1.CurrentPageIndex = 0;
			fill();
			Nrow();
			BindDG();
			
		}
	}
}
I hope this will help you...
Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #16 (permalink)  
Old 01-17-2008, 05:18 AM
a.deeban a.deeban is offline
D-Web Analyst
 
Join Date: May 2007
Posts: 279
a.deeban is on a distinguished road
Default How do I prevent the datagrid from displaying its append row ?

Hi All...

How do I prevent the datagrid from displaying its append row (the row at the end with an asterisk)?

thnkx...
Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #17 (permalink)  
Old 01-17-2008, 05:21 AM
Sathish Kumar Sathish Kumar is offline
D-Web Analyst
 
Join Date: Feb 2007
Posts: 304
Sathish Kumar is on a distinguished road
Thumbs up Re: C#.Net, ASP.Net Data Grid Frequently Asked Questions

Hi,
The DataGrid class does not have a property that controls whether a new row can be added. But the DataView class does have such a property (along with some others such as AllowEdit and AllowDelete).
__________________
Sathish Kumar.R
Knowledge is meant to SHARE
Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #18 (permalink)  
Old 01-17-2008, 05:22 AM
a.deeban a.deeban is offline
D-Web Analyst
 
Join Date: May 2007
Posts: 279
a.deeban is on a distinguished road
Default Re: C#.Net, ASP.Net Data Grid Frequently Asked Questions

Hi Sathish...

Thanks for your reply, can you send me the code using dataview...


thnx again...
Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #19 (permalink)  
Old 01-17-2008, 05:24 AM
Sathish Kumar Sathish Kumar is offline
D-Web Analyst
 
Join Date: Feb 2007
Posts: 304
Sathish Kumar is on a distinguished road
Thumbs up Re: C#.Net, ASP.Net Data Grid Frequently Asked Questions

Hi,
Here is the sample code.

Code:
string connString = @"Provider=Microsoft.JET.OLEDB.4.0;data source=C:\northwind.mdb"; 
 
     string sqlString = "SELECT * FROM customers"; 
 

 
     // Connection object 
 
     OleDbConnection connection = new OleDbConnection(connString); 
 

 
     // Create data adapter object 
 
     OleDbDataAdapter dataAdapter = new OleDbDataAdapter(sqlString, connection); 
 

 
     // Create a dataset object and fill with data using data adapter's Fill method 
 
     DataSet dataSet = new DataSet(); 
 
     dataAdapter.Fill(dataSet, "customers"); 
 
                
 
     // Attach dataset's DefaultView to the datagrid control 
 
     dataGrid1.DataSource = dataSet.Tables["customers"]; 
 

 
     //no adding of new rows thru dataview... 
 
     CurrencyManager cm = (CurrencyManager)this.BindingContext[dataGrid1.DataSource, dataGrid1.DataMember];      
 
     ((DataView)cm.List).AllowNew = false;
__________________
Sathish Kumar.R
Knowledge is meant to SHARE
Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #20 (permalink)  
Old 01-17-2008, 05:27 AM
Sathish Kumar Sathish Kumar is offline
D-Web Analyst
 
Join Date: Feb 2007
Posts: 304
Sathish Kumar is on a distinguished road
Thumbs up Re: C#.Net, ASP.Net Data Grid Frequently Asked Questions

Hi,
If your datagrid contains links, then I would suggest adding Navigate handler such as the one below to disallow the AddNew.

Code:
private void DataGrid1_Navigate(object sender, System.Windows.Forms.NavigateEventArgs ne) 
 
{ 
 
     if(ne.Forward) 
 
     { 
 
          CurrencyManager cm = (CurrencyManager)BindingContext[DataGrid1.DataSource,DataGrid1.DataMember]; 
 
          DataView dv = (DataView) cm.List; 
 
          dv.AllowNew = false; 
 
     } 
 
}
__________________
Sathish Kumar.R
Knowledge is meant to SHARE
Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
Reply


Thread Tools
Display Modes

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

vB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are On


Similar Threads
Thread Thread Starter Forum Replies Last Post
Paging in Grid Kirubhananth ASP and ASP.NET Programming 8 11-28-2008 01:51 AM