datagridview best examples in windows application..

Posted by Gopal_nivas under C# on 4/30/2009 | Views : 57759 | Status : [Member] | Replies : 7
hi.

i want to know datagridview best examples in c#.

need your suggestions regarding this..



regards
gopal




Responses

Posted by: TitoChhabra on: 10/15/2011 [Member] Starter | Points: 25

Up
0
Down
Really this is best example. It's really helpful for me. It's help me lot and this link

http://www.mindstick.com/Articles/37ced6f5-fa75-498d-9eb9-681993fe23be/?Data%20Grid%20View
also helped me to complete my task. Thanks !

Gopal_nivas, if this helps please login to Mark As Answer. | Alert Moderator

Posted by: Gopal_nivas on: 4/30/2009 [Member] Starter

Up
0
Down
Deleting Multiple Rows in a GridView

If you have used Hotmail or any other similar email client, you might have observed that we have the option of selecting multiple rows (using the checkbox provided) and perform a set of operations on them. In this article, we will replicate this scenario for a gridview. A gridview allows us to delete only a single row at a time. We will extend this functionality to select multiple rows and delete all of the selected rows in a single stroke. In this article, I assume that you are aware of creating asp.net web applications and have worked with gridview.
The sample makes use of the Northwind database. We will be pulling data from the Employee table. For this sample to work, drop all the Foreign Key relationships on the Employee Table. To do so, in Sql Server Management Studio, browse to the Northwind database and open the Employee table in design view. Right click in the Table designer on the right hand side and choose 'Relationships'. Select all the relationships like FK_Orders_Employees, FK_EmployeeTerritories_Employees etc and delete them. This step is necessary as we will get a constraint violation exception if we do not do so.
Once we are through with the task of removing the relationships in the Employee table, let us explore the steps to create a gridview with functionality to delete multiple rows at a time.
Perform the following steps :
Step 1: Create an .aspx page and add a GridView and a SqlDataSource control to it.
Step 2: Configure the connection of SqlDataSource to point to the Northwind database. Create queries for the Select and Delete commands. The resultant code will look similar as given below :
<asp:SqlDataSource ID="SqlDataSource1" Runat="server"
SelectCommand="SELECT EmployeeID, LastName, City FROM Employees"
DeleteCommand="DELETE FROM Employees WHERE [EmployeeID] = @EmployeeID"
ConnectionString="<%$ ConnectionStrings:NorthwindConnectionString %>" >
<DeleteParameters>
<asp:Parameter Name="EmployeeID" />
</DeleteParameters>
</asp:SqlDataSource>
Step 3: Once the SqlDataSource has been configured, bind the gridview with this data source.
Step 4: To create a checkbox in each row, follow these steps:
1. Create a TemplateField inside the <Columns> to add custom content to each column.
2. Inside the TemplateField, create an ItemTemplate with a CheckBox added to it.
<asp:TemplateField>
<ItemTemplate>
<asp:CheckBox ID="chkRows" runat="server"/>
</ItemTemplate>
</asp:TemplateField>
This will add a checkbox to each row in the grid.
Step 5: Add a button control, and rename it to btnMultipleRowDelete.
The resultant markup in the design view will look similar to the code below :
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataKeyNames="EmployeeID" DataSourceID="SqlDataSource1">

<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:CheckBox ID="cbRows" runat="server"/>
</ItemTemplate>
</asp:TemplateField>

<asp:BoundField DataField="EmployeeID" HeaderText="EmployeeID" InsertVisible="False" ReadOnly="True" SortExpression="EmployeeID" />
<asp:BoundField DataField="LastName" HeaderText="LastName" SortExpression="LastName" />
<asp:BoundField DataField="City" HeaderText="City" SortExpression="City" />
</Columns>
</asp:GridView>

<asp:SqlDataSource ID="SqlDataSource1" Runat="server"
SelectCommand="SELECT EmployeeID, LastName, City FROM Employees"
DeleteCommand="DELETE FROM Employees WHERE [EmployeeID] = @EmployeeID"
ConnectionString="<%$ ConnectionStrings:NorthwindConnectionString %>" >
<DeleteParameters>
<asp:Parameter Name="EmployeeID" />
</DeleteParameters>
</asp:SqlDataSource>

<asp:Button
ID="btnMultipleRowDelete"
OnClick="btnMultipleRowDelete_Click"
runat="server"
Text="Delete Rows" />

In Code behind file (.cs) for C# and (.vb) for VB.NET, code the button click event. Our code will first loop through all the rows in the GridView. If a row is checked, the code retrieves the EmployeeID and passes the selected value to the Delete Command.
C#


protected void btnMultipleRowDelete_Click(object sender, EventArgs e)
{
// Looping through all the rows in the GridView
foreach (GridViewRow row in GridView1.Rows)
{
CheckBox checkbox = (CheckBox)row.FindControl("cbRows");

//Check if the checkbox is checked.
//value in the HtmlInputCheckBox's Value property is set as the //value of the delete command's parameter.
if (checkbox.Checked)
{
// Retreive the Employee ID
int employeeID = Convert.ToInt32(GridView1.DataKeys[row.RowIndex].Value);
// Pass the value of the selected Employye ID to the Delete //command.
SqlDataSource1.DeleteParameters["EmployeeID"].DefaultValue = employeeID.ToString();
SqlDataSource1.Delete();
}
}
}

Gopal_nivas, if this helps please login to Mark As Answer. | Alert Moderator

Posted by: Gopal_nivas on: 4/30/2009 [Member] Starter

Up
0
Down
<script language="javascript" type="text/javascript">

function ConfirmDelete()

{

return confirm("Are u sure u want to delete all these records?")

}

</script>



<asp:GridView ID="GridView1" runat="server" AllowPaging="True" AllowSorting="True"

AutoGenerateColumns="False" DataSourceID="SqlDataSource1" DataKeyNames="CustomerID">

<Columns>

<asp:TemplateField>

<ItemTemplate>

<asp:CheckBox ID="chkgrid" runat="server"/>

</ItemTemplate>

</asp:TemplateField>

<asp:BoundField DataField="CustomerID" Visible="false"/>

<asp:BoundField DataField="CompanyName" HeaderText="CompanyName" SortExpression="CompanyName" />

<asp:BoundField DataField="ContactName" HeaderText="ContactName" SortExpression="ContactName" />

<asp:BoundField DataField="Country" HeaderText="Country" SortExpression="Country" />

</Columns>

</asp:GridView>

<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:dbPDMS_V1.5ConnectionString6 %>"

SelectCommand="SELECT [CustomerID], [CompanyName], [ContactName], [Country] FROM [Customer]" DeleteCommand="Delete from [Customer] where [CustomerID]=@Customerid">

<DeleteParameters>

<asp:Parameter Name="CustomerID"/>

</DeleteParameters>

</asp:SqlDataSource>

<asp:Button ID="btndelete" Text="delete" runat="server" OnClick="btndelete_click" OnClientClick="return ConfirmDelete()"/>



code behind:

using System;

using System.Data;

using System.Configuration;

using System.Collections;

using System.Web;

using System.Web.Security;

using System.Web.UI;

using System.Web.UI.WebControls;

using System.Web.UI.WebControls.WebParts;

using System.Web.UI.HtmlControls;

public partial class batchDelete : System.Web.UI.Page

{

protected void Page_Load(object sender, EventArgs e)

{

}

protected void btndelete_click(object sender ,EventArgs e)

{

foreach(GridViewRow row in GridView1. Rows)

{

CheckBox cb = (CheckBox)row.FindControl("chkgrid");

if(cb.Checked)

{

int customerid = Convert.ToInt32(GridView1.DataKeys[row.RowIndex].Value);

SqlDataSource1.DeleteParameters["CustomerID"].DefaultValue = customerid.ToString();

SqlDataSource1.Delete();


}

}

}

}
dilshad.

Gopal_nivas, if this helps please login to Mark As Answer. | Alert Moderator

Posted by: Vuyiswamb on: 4/30/2009 [Member] [MVP] [Administrator] NotApplicable

Up
0
Down
Good Afternoon Gopal_nivas

There are Plenty of Examples, but as you did not mentioned what Gridview Examples , i might as well give you all i can

check this

http://www.codeproject.com/KB/cs/N-Tier22.aspx?display=PrintAll


http://www.dotnetfunda.com/interview/exam351-what-is-the-difference-gridview-and-between-datagridwindows.aspx

http://www.dotnetfunda.com/articles/article138.aspx

http://www.codeproject.com/KB/aspnet/EditNestedGridView.aspx


http://www.dotnetfunda.com/articles/article224.aspx


http://www.codeproject.com/KB/aspnet/MultiNestMDGridview.aspx

http://www.codeproject.com/KB/ajax/GridViewKeyboardExtender.aspx

http://www.codeproject.com/KB/webforms/States_of_CheckBoxes.aspx

http://www.codeproject.com/KB/webforms/GridViewConfirmDelete.aspx

http://www.codeproject.com/KB/webforms/GridViewSortIndicator.aspx

http://www.codeproject.com/KB/webforms/SelChkboxesDataGridView.aspx

http://www.codeproject.com/KB/aspnet/SQL_Injection_.aspx

http://www.codeproject.com/KB/aspnet/Paging_without_a_Wizard.aspx

http://www.codeproject.com/KB/cs/N-Tier22.aspx

Thank you forp Posting at Dotnetfunda

Vuyiswa Maseko

Thank you for posting at Dotnetfunda
[Administrator]

Gopal_nivas, if this helps please login to Mark As Answer. | Alert Moderator

Posted by: Asa on: 5/4/2009 [Member] Starter

Up
0
Down
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Data.OleDb;
using System.Data.Odbc;
using Excel = Microsoft.Office.Interop.Excel;
using System.Reflection;
using System.Collections;
using System.Threading;
using System.Data.SqlClient;


namespace DBASE
{
public partial class DDREPGEN : Form
{
public DDREPGEN()
{
InitializeComponent();

DateTime date = new DateTime();
date.GetDateTimeFormats();
timer1.Start();
date_label.Text = System.DateTime.Today.ToShortDateString();

//tread: http://www.suite101.com/article.cfm/c_sharp/96436
}


public Label qurey_label;
private OdbcConnection conn;
private OdbcConnectionStringBuilder osb = new OdbcConnectionStringBuilder();
private OdbcDataAdapter oleDbDataAdapter1;
DataTable dt = new DataTable();
DataTable dt2 = new DataTable();
//DataSet ds = new DataSet();


private void ClearDataSet(DataSet myDataSet)
{
// To test, print the number rows in each table.
foreach (DataTable dt in myDataSet.Tables)
{
Console.WriteLine(dt.TableName + "Rows.Count = " + dt.Rows.Count.ToString());
}
// Clear all rows of each table.
myDataSet.Clear();
// Print the number of rows again.
foreach (DataTable dt in myDataSet.Tables)
{
Console.WriteLine(dt.TableName + "Rows.Count = " + dt.Rows.Count.ToString());
}
}


private void buttonViewData_Click(object sender, EventArgs e)
{
//show in data grid
if (radioButtonBooth.Checked == true)
{
dataSet2.Clear();
//dataGrid1.DataSource dataSet1.dt.DefaultView;
dataGridViewBooth.DataSource = dt.DefaultView;
dataGridViewCash.Visible = false;
dataGridViewBooth.Visible = true;
//dataGridViewBooth.ClearSelection();
//ds.Clear();
dataGridViewBooth.DataSource = dt;
buttonExportData.Enabled = true;
buttonViewData.Enabled = false;

}
else if (radioButtonCash.Checked == true)
{
dataSet2.Clear();
dataGridViewCash.DataSource = dt.DefaultView;
dataGridViewBooth.Visible = false;
dataGridViewCash.Visible = true;
//dataGridViewCash.ClearSelection();
//ds.Clear();
dataGridViewCash.DataSource = dt;
buttonExportData.Enabled = true;
buttonViewData.Enabled = false;
}
}

private void buttonExit_Click(object sender, EventArgs e)
{
this.Close();
}

private void Form1_Load(object sender, EventArgs e)
{
}



private void buttonExportData_Click(object sender, EventArgs e)
{
DialogResult reply = MessageBox.Show("Are you sure you want to Export this data to excel?","TRANSPORTER",MessageBoxButtons.YesNo); //inform the user

if( reply == DialogResult.Yes)
{

//testing import
Excel.Application oXL;
Excel._Workbook oWB;
Excel._Worksheet oSheet;
Excel.Range oRng;

try
{

TextBox textBox1 = new TextBox();
string[,] arr = new string[1000, 2];

//Start Excel and get Application object.
oXL = new Excel.Application();
oXL.Visible = true;

//Get a new workbook.
oWB = (Excel._Workbook)(oXL.Workbooks.Add(Missing.Value));
oSheet = (Excel._Worksheet)oWB.ActiveSheet;
if (radioButtonCash.Checked == true)
{
//Add table headers going cell by cell.
oSheet.Cells[1, 4] = "Golden Donuts Inc.";
oSheet.Cells[2, 4] = "SAMPLE QUERY";
oSheet.Cells[2, 1] = "Shop:";
oSheet.Cells[2, 2] = shop_comboBox.Text.ToString();
oSheet.Cells[4, 1] = "Location:";
oSheet.Cells[4, 2] = location_textBox.Text.ToString();
oSheet.Cells[3, 1] = "Account No.";
oSheet.Cells[3, 2] = account_textBox.Text.ToString();
oSheet.Cells[5, 1] = "NET_SALES";
oSheet.Cells[5, 3] = "OVERAGES";
oSheet.Cells[5, 2] = "SHOP_VAT";
}
else if (radioButtonBooth.Checked == true)
{ //Add table headers going cell by cell
oSheet.Cells[1, 4] = "Golden Donuts Inc.";
oSheet.Cells[2, 4] = "BOOTH SALES";
oSheet.Cells[2, 1] = "Shop:";
oSheet.Cells[2, 2] = shop_comboBox.Text.ToString();
oSheet.Cells[4, 1] = "Location:";
oSheet.Cells[4, 2] = location_textBox.Text.ToString();
oSheet.Cells[3, 1] = "Account No.";
oSheet.Cells[3, 2] = account_textBox.Text.ToString();
oSheet.Cells[5, 1] = "DATE";
oSheet.Cells[5, 2] = "# CUST";
oSheet.Cells[5, 3] = "NET SALES";
oSheet.Cells[5, 4] = "TOTAL";
oSheet.Cells[5, 5] = "A/R - E";
oSheet.Cells[5, 6] = "TOTAL";
oSheet.Cells[5, 7] = "VAT";
oSheet.Cells[5, 8] = "OVERAGES";
oSheet.Cells[5, 9] = "OTHERS";
}
else
{
}


//AutoFit col

Gopal_nivas, if this helps please login to Mark As Answer. | Alert Moderator

Posted by: Asa on: 5/4/2009 [Member] Starter

Up
0
Down
.....umns A:D.
oRng = oSheet.get_Range("A1", "I1");
oRng.EntireColumn.AutoFit();
oRng.EntireRow.AutoFit();

//Format A1:D1 as bold, vertical alignment = center.
oSheet.get_Range("A1", "j5").Font.Bold = true;
oSheet.get_Range("a1", "j1").Font.Size = 14;

//oSheet.get_Range("b2", "c4").Font.Color = Color.Bisque;
oSheet.get_Range("A1", "D1").VerticalAlignment =
Excel.XlVAlign.xlVAlignCenter;

// Create an array to multiple values at once.
string[,] saNames = new string[5, 2];

saNames[0, 0] = "ABS-CBN";
saNames[0, 1] = "kapuso";
saNames[1, 0] = "GMA";
saNames[1, 1] = "kapamilya";

if (radioButtonCash.Checked == true)
{


int rIndex = 6;
int cIndex = 1;
int dataRowIndex = 0;
int ctr = 0;

ArrayList data = new ArrayList();
data.Clear();

foreach (DataRow row in dt.Rows)
{
foreach (DataColumn column in dt.Columns)
{
//UNG MESSAGE LUMALABAS PA...ITONG NEXT MAGEEROR NA!!!
data.Add(row[column.ColumnName] + "");
ctr++;
}
}

foreach (string arraydata in data)
{

if (cIndex != 4)
{
oXL.Cells[rIndex, cIndex] = data[dataRowIndex];
cIndex++;
dataRowIndex++;

if (cIndex == 4)
{
cIndex = 1;

rIndex++;
}
}
}

}
else if (radioButtonBooth.Checked == true)
{

int rIndex = 6;
int cIndex = 1;
int dataRowIndex = 0;
int ctr = 0;

ArrayList data = new ArrayList();
data.Clear();


foreach (DataRow row in dt.Rows)
{
foreach (DataColumn column in dt.Columns)
{
//UNG MESSAGE LUMALABAS PA...ITONG NEXT MAGEEROR NA!!!
data.Add(row[column.ColumnName] + "");
ctr++;
}
}

foreach (string arraydata in data)
{

if (cIndex != 10)
{
oXL.Cells[rIndex, cIndex] = data[dataRowIndex];
cIndex++;
dataRowIndex++;

if (cIndex == 10)
{
cIndex = 1;

rIndex++;
}
}
}
}
else
{
}

//Make sure Excel is visible and give the user control
//of Microsoft Excel's lifetime.
oXL.Visible = true;
oXL.UserControl = true;
}
catch (Exception theException)
{
String errorMessage;
errorMessage = "Error: ";
errorMessage = String.Concat(errorMessage, theException.Message);
errorMessage = String.Concat(errorMessage, " Line: ");
errorMessage = String.Concat(errorMessage, theException.Source);

MessageBox.Show(errorMessage, "Error");
}
buttonExportData.Enabled = false;
shop_comboBox.Enabled = false;
panel1.Enabled = false;
// DialogResult reply1 = MessageBox.Show("TERMINATE GENERATOR?", "CLOSE", MessageBoxButtons.YesNo);
//if (reply1 == DialogResult.Yes)
//{
// this.Close();
// }
//else
//{
shop_comboBox.Text = "";
shop_comboBox.Enabled = true;
radioButtonBooth.Checked = false;
radioButtonCash.Checked = false;
CRBS_radioButton.Checked = false;
// }

}
else
{
buttonExportData.Enabled = true;//MessageBox.Show("false");
}


}

private void radioButtonCash_CheckedChanged_1(object sender, EventArgs e)
{
//this.ClearDataSet();
//ds.Clear();
//dataSet2.Clear();
// dataGridViewCash.Rows.Clear();
//dataGridViewBooth.Rows.Clear();
buttonViewData.Enabled = true;
conn = new OdbcConnection("Dsn=mydbf");
oleDbDataAdapter1 = new OdbcDataAdapter();

//dt.Rows.Clear();
//dataGridViewBooth.Rows.Clear();e


//dataGridViewBooth.DataSource = dt2;
//dt

Gopal_nivas, if this helps please login to Mark As Answer. | Alert Moderator

Posted by: Asa on: 5/4/2009 [Member] Starter

Up
0
Down
....//dataGridViewBooth.DataSource = dt2;
//dt.Clear();
// dt.Rows.Clear();
try
{
this.conn.Open();
// MessageBox.Show("opened DBF DATABASE", "open", MessageBoxButtons.OK);

System.Data.Odbc.OdbcCommand oCmd = conn.CreateCommand();
oCmd.CommandText = @"SELECT NET_SALE, SHOP_VAT, OVERAGES FROM BOOTHTXN.DBF WHERE SHOPCODE = '357'";
dt.Load(oCmd.ExecuteReader());
this.conn.Close();

// MessageBox.Show("CLOSE DATABASE", "BYE!", MessageBoxButtons.OK);

}
catch (System.Data.Odbc.OdbcException exp)
{
//close the connection
this.conn.Close();
MessageBox.Show("close conn");
MessageBox.Show(exp.ToString());
}

}

private void shop_comboBox_SelectedIndexChanged(object sender, EventArgs e)
{
panel1.Enabled = true;
}

private void radioButtonBooth_CheckedChanged(object sender, EventArgs e)
{

//dataSet2.Clear();
//dataGridViewBooth.Rows.Clear();
// dataGridViewCash.Rows.Clear();
conn = new OdbcConnection("Dsn=mydbf");
oleDbDataAdapter1 = new OdbcDataAdapter();
//dataGridViewBooth.DataSource = dt2;
//dt.Clear();
//dt.Rows.Clear();



try
{

this.conn.Open();
//MessageBox.Show("opened DBF DATABASE", "open", MessageBoxButtons.OK);

System.Data.Odbc.OdbcCommand oCmd = conn.CreateCommand();
oCmd.CommandText = @"SELECT BOOTHTXN.[TXN_DATE], BOOTHTXN.[NUM_CUST], BOOTHTXN.[NET_SALE], BOOTHTXN.[SHOPCASH], BOOTHTXN.[SHOP_ARE], ([NET_SALE]+[SHOP_VAT]+[OVERAGES]) AS TOTAL, BOOTHTXN.[SHOP_VAT], BOOTHTXN.[OVERAGES], BOOTHTXN.[SHOP_OTH]
FROM BOOTHTXN
where boothtxn.[brancode] = '07' and boothtxn.[shopcode] = '300'";
//oCmd.CommandText = @"SELECT BOOTHTXN.BRANCODE, BOOTHTXN.SHOPCODE, SALESFLE.TERMINAL, SALESFLE.TXN_TYPE
// FROM SALESFLE INNER JOIN BOOTHTXN ON SALESFLE.BRANCODE = BOOTHTXN.BRANCODE
// WHERE (((BOOTHTXN.BRANCODE)='07'))";
//oCmd.CommandText = @"SELECT * FROM BOOTHTXN.DBF INNER JOIN SALESFLE.DBF WHERE BOOTHTXN.BRANCODE = SALESFLE.BRANCODE";
//oCmd.CommandText = @"SELECT PLU_MAST.ITEMDESC FROM PLU_MAST,SALESFLE WHERE PLU_MAST.ITEMCODE = SALESFLE.ITEMCODE";
dt.Load(oCmd.ExecuteReader());

this.conn.Close();
//MessageBox.Show("CLOSE DATABASE", "BYE!", MessageBoxButtons.OK);
buttonViewData.Enabled = true;
}
catch (System.Data.Odbc.OdbcException exp)
{
//close the connection

this.conn.Close();
MessageBox.Show("close conn");
MessageBox.Show(exp.ToString());
}
}

private void CRBS_radioButton_CheckedChanged(object sender, EventArgs e)
{
dataGridViewBooth.ClearSelection();
buttonViewData.Enabled = true;
dataGridViewBooth.DataSource = dt2;
dt.Clear();

}



private void timer1_Tick(object sender, EventArgs e)
{
DateTime dtime = DateTime.Now;
time_label.Text = dtime.Hour + ":" + dtime.Minute + ":" + dtime.Second;
Thread.Sleep(1000);
}


}


}

Gopal_nivas, if this helps please login to Mark As Answer. | Alert Moderator

Login to post response