Click here to Skip to main content
15,880,392 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi
I need your help. i make an app in which data load from excel file into datagrid view but it also load column name i just want to load values to specif column
C#
try
{
    string pathcon = "Provider = Microsoft.ACE.OLEDB.12.0; Data Source =" + textBox_path.Text + "; Extended Properties = 'Excel 8.0;HDR=yes;IMEX=1'";
    OleDbConnection conn = new OleDbConnection(pathcon);
    OleDbDataAdapter myadapter = new OleDbDataAdapter("select Clients from[" + textBox_sheet_no.Text + "$A2]", conn);
    DataTable dt = new DataTable();
    myadapter.Fill(dt);
    dataGridView_VAT.DataSource = dt;
}
catch (Exception e1)
{
    MessageBox.Show("Error in Connection " + e1.Message);
}

//this is my code but i want to show like
DataGridViewRow row = new DataGridViewRow();
row.CreateCells(dataGridView_VAT);
row.Cells[0].Value = 
row.Cells[1].Value = 
row.Cells[2].Value = 
row.Cells[3].Value =
row.Cells[4].Value = 
row.Cells[5].Value = 
dataGridView_VAT.Rows.Add(row);


[Edit member="Tadit"]
Added pre tags.
[/Edit]
Posted
v2
Comments
Francine DeGrood Taylor 13-Jun-14 18:27pm    
What are you trying to do? Do you just want to give the datagridview columns the same name as the columns that they were filled from? Or do you want to create the columns first, in a particular order and load them with data from the corresponding column?
Member 10393648 14-Jun-14 0:55am    
yes i want to create the columns first, in a particular order and load them with data from the corresponding column from excel file
RDBurmon 15-Jun-14 2:37am    
Isn't you excel has fixed sequence of columns?

1 solution

If I correctly understand what you want, this should be a solution for you.

1. Create predefined columns.
C#
private System.Windows.Forms.DataGridViewTextBoxColumn column1;
private System.Windows.Forms.DataGridViewTextBoxColumn column2;


2. Set the DataPropertyName to the Excel column name.
C#
this.column1.DataPropertyName = "ExcelCol1";
this.column1.HeaderText = "Col1";
this.column1.Name = "column1";
this.column1.Width = 50;

this.column2.DataPropertyName = "ExcelCol2";
this.column2.HeaderText = "Col2";
this.column2.Name = "column2";
this.column2.Width = 50;


3. Add the columns to the DataGridView
C#
this.dataGridView_VAT.Columns.AddRange(
new System.Windows.Forms.DataGridViewColumn[] {
            this.column1,
            this.column2});


Now when you fill the DataTable with values they will fall into the right columns and you can reorder the columns as you please, as the name of the column is the key, not the index.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900