Use the new keyword to create an object BindingSource data = dataGridView.DataSource as BindingSour

EDN Admin

Well-known member
Joined
Aug 7, 2010
Messages
12,794
Location
In the Machine
Please help to resolve this problem on my program to get datagridview autofilter feature . I am trying to display the record from an excel sheet into gridview with autofilter feature.
I have given my program in my code block. The error is coming is from here
<span style="text-decoration:underline <span style="color:#2b91af; font-family:Consolas; font-size:x-small <span style="color:#2b91af; font-family:Consolas; font-size:x-small <span style="color:#2b91af; font-family:Consolas; font-size:x-small BindingSource<span style="font-family:Consolas; font-size:x-small <span style="font-family:Consolas; font-size:x-small
data = dataGridView.DataSource <span style="color:#0000ff; font-family:Consolas; font-size:x-small <span style="color:#0000ff; font-family:Consolas; font-size:x-small <span style="color:#0000ff; font-family:Consolas; font-size:x-small as<span style="font-family:Consolas; font-size:x-small <span style="font-family:Consolas; font-size:x-small
<span style="color:#2b91af; font-family:Consolas; font-size:x-small <span style="color:#2b91af; font-family:Consolas; font-size:x-small <span style="color:#2b91af; font-family:Consolas; font-size:x-small BindingSource<span style="font-family:Consolas; font-size:x-small <span style="font-family:Consolas; font-size:x-small ;
<span style="text-decoration:underline <span style="color:#2b91af; font-family:Consolas; font-size:x-small <span style="color:#2b91af; font-family:Consolas; font-size:x-small <span style="color:#2b91af; font-family:Consolas; font-size:x-small Int32 <span style="font-family:Consolas; font-size:x-small <span style="font-family:Consolas; font-size:x-small <span style="text-decoration:underline
currentRowCount = data.Count;

<span style="font-family:Consolas; font-size:x-small <span style="font-family:Consolas; font-size:x-small My allprogram attached herewith in code block. Please help <span style="font-family:Consolas; font-size:x-small <span style="font-family:Consolas; font-size:x-small

<pre>DataGridViewAutoFilterColumnHeaderCell.cs
using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;
using System.ComponentModel;
namespace ImportandExportexcel
{
public class DataGridViewAutoFilterTextBoxColumn : DataGridViewTextBoxColumn
{

/// <summary>
/// Initializes a new instance of the DataGridViewAutoFilterTextBoxColumn class.
/// </summary>
public DataGridViewAutoFilterTextBoxColumn() : base()
{
base.DefaultHeaderCellType = typeof(DataGridViewAutoFilterColumnHeaderCell);
base.SortMode = DataGridViewColumnSortMode.Programmatic;
}

#region public properties that hide inherited, non-virtual properties: DefaultHeaderCellType and SortMode

/// <summary>
/// Returns the AutoFilter header cell type. This property hides the
/// non-virtual DefaultHeaderCellType property inherited from the
/// DataGridViewBand class. The inherited property is set in the
/// DataGridViewAutoFilterTextBoxColumn constructor.
/// </summary>
[EditorBrowsable(EditorBrowsableState.Never), Browsable(false),
DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public new Type DefaultHeaderCellType
{
get
{
return typeof(DataGridViewAutoFilterColumnHeaderCell);
}
}

/// <summary>
/// Gets or sets the sort mode for the column and prevents it from being
/// set to Automatic, which would interfere with the proper functioning
/// of the drop-down button. This property hides the non-virtual
/// DataGridViewColumn.SortMode property from the designer. The inherited
/// property is set in the DataGridViewAutoFilterTextBoxColumn constructor.
/// </summary>
[EditorBrowsable(EditorBrowsableState.Advanced), Browsable(false)]
[DefaultValue(DataGridViewColumnSortMode.Programmatic)]
public new DataGridViewColumnSortMode SortMode
{
get
{
return base.SortMode;
}
set
{
if (value == DataGridViewColumnSortMode.Automatic)
{
throw new InvalidOperationException(
"A SortMode value of Automatic is incompatible with " +
"the DataGridViewAutoFilterColumnHeaderCell type. " +
"Use the AutomaticSortingEnabled property instead.");
}
else
{
base.SortMode = value;
}
}
}

#endregion

#region public properties: FilteringEnabled, AutomaticSortingEnabled, DropDownListBoxMaxLines

/// <summary>
/// Gets or sets a value indicating whether filtering is enabled for this column.
/// </summary>
[DefaultValue(true)]
public Boolean FilteringEnabled
{
get
{
// Return the header-cell value.
return ((DataGridViewAutoFilterColumnHeaderCell)HeaderCell)
.FilteringEnabled;
}
set
{
// Set the header-cell property.
((DataGridViewAutoFilterColumnHeaderCell)HeaderCell)
.FilteringEnabled = value;
}
}

/// <summary>
/// Gets or sets a value indicating whether automatic sorting is enabled for this column.
/// </summary>
[DefaultValue(true)]
public Boolean AutomaticSortingEnabled
{
get
{
// Return the header-cell value.
return ((DataGridViewAutoFilterColumnHeaderCell)HeaderCell)
.AutomaticSortingEnabled;
}
set
{
// Set the header-cell property.
((DataGridViewAutoFilterColumnHeaderCell)HeaderCell)
.AutomaticSortingEnabled = value;
}
}

/// <summary>
/// Gets or sets the maximum height of the drop-down filter list for this column.
/// </summary>
[DefaultValue(20)]
public Int32 DropDownListBoxMaxLines
{
get
{
// Return the header-cell value.
return ((DataGridViewAutoFilterColumnHeaderCell)HeaderCell)
.DropDownListBoxMaxLines;
}
set
{
// Set the header-cell property.
((DataGridViewAutoFilterColumnHeaderCell)HeaderCell)
.DropDownListBoxMaxLines = value;
}
}

#endregion public properties

#region public, static, convenience methods: RemoveFilter and GetFilterStatus

/// <summary>
/// Removes the filter from the BindingSource bound to the specified DataGridView.
/// </summary>
/// <param name="dataGridView The DataGridView bound to the BindingSource to unfilter.</param>
public static void RemoveFilter(DataGridView dataGridView)
{
DataGridViewAutoFilterColumnHeaderCell.RemoveFilter(dataGridView);
}

/// <summary>
/// Gets a status string for the specified DataGridView indicating the
/// number of visible rows in the bound, filtered BindingSource, or
/// String.Empty if all rows are currently visible.
/// </summary>
/// <param name="dataGridView The DataGridView bound to the
/// BindingSource to return the filter status for.</param>
/// <returns>A string in the format "x of y records found" where x is
/// the number of rows currently displayed and y is the number of rows
/// available, or String.Empty if all rows are currently displayed.</returns>
public static String GetFilterStatus(DataGridView dataGridView)
{
return DataGridViewAutoFilterColumnHeaderCell.GetFilterStatus(dataGridView);
}

#endregion
}



}
[/code]
<pre>Form1.cs
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;


namespace ImportandExportexcel
{
public partial class Form1 : Form
{
string strfile;
public Form1()
{
InitializeComponent();
}

private void Browse_Click(object sender, EventArgs e)
{
OpenFileDialog ofd = new OpenFileDialog();
ofd.Title = "Select Excel file only";
ofd.CheckFileExists = false;
ofd.CheckPathExists = true;
ofd.AddExtension = true;
ofd.DefaultExt = "txt";
ofd.ShowReadOnly = true;
ofd.ShowHelp = true;
if (ofd.ShowDialog() == DialogResult.Cancel)
Application.Exit();
strfile = ofd.FileName.ToString();
}

private void button1_Click(object sender, EventArgs e)
{
DataSet objDataset1 = new DataSet();
string ConnectionString = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + strfile + ";Extended Properties=Excel 5.0";
OleDbConnection objConn = new OleDbConnection(ConnectionString);
objConn.Open();
String strConString = "SELECT * from [Sheet1$]";
OleDbCommand objCmdSelect = new OleDbCommand(strConString, objConn);
OleDbDataAdapter objAdapter1 = new OleDbDataAdapter();
objAdapter1.SelectCommand = objCmdSelect;
DataTable dt = new DataTable();
objAdapter1.Fill(objDataset1, "ExcelData");
dataGridView1.DataSource = objDataset1.Tables[0];
objConn.Close();

}

private void button2_Click(object sender, EventArgs e)
{
DataTable dt = (DataTable)dataGridView1.DataSource;
exportToExcel(dt, "c:\Exportedtoexcel.xls");
MessageBox.Show("Exported to Excel successfully");
}
public static void exportToExcel(DataTable source, string fileName)
{

System.IO.StreamWriter excelDoc;

excelDoc = new System.IO.StreamWriter(fileName);
const string startExcelXML = "<xml version>rn<Workbook " +
"xmlns="urn:schemas-microsoft-com:office:spreadsheet"rn" +
" xmlns:o="urn:schemas-microsoft-com:office:office"rn " +
"xmlns:x="urn:schemas- microsoft-com:office:" +
"excel"rn xmlns:ss="urn:schemas-microsoft-com:" +
"office:spreadsheet rn <Styles>rn " +
"<Style ss:ID="Default" ss:Name="Normal rn " +
"<Alignment ss:Vertical="Bottom"/>rn <Borders/>" +
"rn <Font/>rn <Interior/>rn <NumberFormat/>" +
"rn <Protection/>rn </Style>rn " +
"<Style ss:ID="BoldColumn rn <Font " +
"x:Family="Swiss" ss:Bold="1"/>rn </Style>rn " +
"<Style ss:ID="StringLiteral rn <NumberFormat" +
" ss:Format="@"/>rn </Style>rn <Style " +
"ss:ID="Decimal rn <NumberFormat " +
"ss:Format="0.0000"/>rn </Style>rn " +
"<Style ss:ID="Integer rn <NumberFormat " +
"ss:Format="0"/>rn </Style>rn <Style " +
"ss:ID="DateLiteral rn <NumberFormat " +
"ss:Format="mm/dd/yyyy;@"/>rn </Style>rn " +
"</Styles>rn ";
const string endExcelXML = "</Workbook>";

int rowCount = 0;
int sheetCount = 1;
excelDoc.Write(startExcelXML);
excelDoc.Write("<Worksheet ss:Name="Test" + sheetCount + " ");
excelDoc.Write("<Table>");
excelDoc.Write("<Row>");

for (int x = 0; x < source.Columns.Count; x++)
{
excelDoc.Write("<Cell ss:StyleID="BoldColumn <Data ss:Type="String ");

excelDoc.Write(source.Columns[x].ColumnName);
excelDoc.Write("</Data></Cell>");
}
excelDoc.Write("</Row>");


foreach (DataRow x in source.Rows)
{
rowCount++;
//if the number of rows is > 64000 create a new page to continue output
if (rowCount == 64000)
{
rowCount = 0;
sheetCount++;
excelDoc.Write("</Table>");
excelDoc.Write(" </Worksheet>");
excelDoc.Write("<Worksheet ss:Name="Sheet" + sheetCount + " ");
excelDoc.Write("<Table>");
}
excelDoc.Write("<Row>"); //ID=" + rowCount + "

for (int y = 0; y < source.Columns.Count; y++)
{
System.Type rowType;
rowType = x[y].GetType();
switch (rowType.ToString())
{
case "System.String":
string XMLstring = x[y].ToString();
XMLstring = XMLstring.Trim();
XMLstring = XMLstring.Replace("&", "&");
XMLstring = XMLstring.Replace( ", ");
XMLstring = XMLstring.Replace("<", "<");
excelDoc.Write("<Cell ss:StyleID="StringLiteral " +
"<Data ss:Type="String ");
excelDoc.Write(XMLstring);
excelDoc.Write("</Data></Cell>");
break;
case "System.DateTime":
//Excel has a specific Date Format of YYYY-MM-DD followed by
//the letter T then hh:mm:sss.lll Example 2005-01-31T24:01:21.000
//The Following Code puts the date stored in XMLDate
//to the format above
DateTime XMLDate = (DateTime)x[y];
string XMLDatetoString = ""; //Excel Converted Date
XMLDatetoString = XMLDate.Year.ToString() +
"-" +
(XMLDate.Month < 10 ? "0" +
XMLDate.Month.ToString() : XMLDate.Month.ToString()) +
"-" +
(XMLDate.Day < 10 ? "0" +
XMLDate.Day.ToString() : XMLDate.Day.ToString()) +
"T" +
(XMLDate.Hour < 10 ? "0" +
XMLDate.Hour.ToString() : XMLDate.Hour.ToString()) +
":" +
(XMLDate.Minute < 10 ? "0" +
XMLDate.Minute.ToString() : XMLDate.Minute.ToString()) +
":" +
(XMLDate.Second < 10 ? "0" +
XMLDate.Second.ToString() : XMLDate.Second.ToString()) +
".000";
excelDoc.Write("<Cell ss:StyleID="DateLiteral " +
"<Data ss:Type="DateTime ");
excelDoc.Write(XMLDatetoString);
excelDoc.Write("</Data></Cell>");
break;
case "System.Boolean":
excelDoc.Write("<Cell ss:StyleID="StringLiteral " +
"<Data ss:Type="String ");
excelDoc.Write(x[y].ToString());
excelDoc.Write("</Data></Cell>");
break;
case "System.Int16":
case "System.Int32":
case "System.Int64":
case "System.Byte":
excelDoc.Write("<Cell ss:StyleID="Integer " +
"<Data ss:Type="Number ");
excelDoc.Write(x[y].ToString());
excelDoc.Write("</Data></Cell>");
break;
case "System.Decimal":
case "System.Double":
excelDoc.Write("<Cell ss:StyleID="Decimal " +
"<Data ss:Type="Number ");
excelDoc.Write(x[y].ToString());
excelDoc.Write("</Data></Cell>");
break;
case "System.DBNull":
excelDoc.Write("<Cell ss:StyleID="StringLiteral " +
"<Data ss:Type="String ");
excelDoc.Write("");
excelDoc.Write("</Data></Cell>");
break;
default:
throw (new Exception(rowType.ToString() + " not handled."));
}
}
excelDoc.Write("</Row>");
}
excelDoc.Write("</Table>");
excelDoc.Write(" </Worksheet>");
excelDoc.Write(endExcelXML);




excelDoc.Close();
}

private void Form1_Load(object sender, EventArgs e)
{
this.dataGridView1.AutoResizeColumns();
}
private void dataGridView1_KeyDown(object sender, KeyEventArgs e)
{
if (e.Alt && (e.KeyCode == Keys.Down || e.KeyCode == Keys.Up))
{
DataGridViewAutoFilterColumnHeaderCell filterCell =
dataGridView1.CurrentCell.OwningColumn.HeaderCell as
DataGridViewAutoFilterColumnHeaderCell;
if (filterCell != null)
{
filterCell.ShowDropDownList();
e.Handled = true;
}
}
}
private void dataGridView1_DataBindingComplete(object sender,
DataGridViewBindingCompleteEventArgs e)
{
String filterStatus = DataGridViewAutoFilterColumnHeaderCell
.GetFilterStatus(dataGridView1);
if (String.IsNullOrEmpty(filterStatus))
{
// showAllLabel.Visible = false;
// filterStatusLabel.Visible = false;
}
else
{
// showAllLabel.Visible = true;
// filterStatusLabel.Visible = true;
//filterStatusLabel.Text = filterStatus;
}
}
}
}
[/code]
<br/>
<br/>



<hr class="sig polachan

View the full article
 
Back
Top