0

Im having trouble displaying specific columns from excel to c# in data grid view. i dont know what is the syntax to display specific columns. im using oledb for displaying da data.

Here's my code:

    private void WorkOrderTab()
    {
        string filePath = Path.GetFullPath(WOmain);
        string extension = Path.GetExtension(filePath);
        string conStr, sheetName;
        conStr = string.Empty;
        //Get the name of the First Sheet.
        using (OleDbConnection kuneksyon = new OleDbConnection(Excel07ConString))
        {
            using (OleDbCommand utos = new OleDbCommand())
            { 
                using (OleDbDataAdapter oda = new OleDbDataAdapter())
                {
                utos.Connection = kuneksyon;
                kuneksyon.Open();
                DataTable dtExcelSchema = kuneksyon.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
                sheetName = dtExcelSchema.Rows[0]["TABLE_NAME"].ToString();
                kuneksyon.Close();
                DataTable dt = new DataTable();
                utos.Connection = kuneksyon;
                utos.CommandText = "SELECT * From [" + sheetName + "]";
                kuneksyon.Open();
                oda.SelectCommand = utos;
                oda.Fill(dt);
                kuneksyon.Close();
                //Populate DataGridView.
                WorkLoadDisp.DataSource = dt;
                label1.Text = dt.Rows.Count.ToString();
                }
            }
        }
    }
  • If your worksheet has HEADERS in its first row, those headers are the column names, if no headers then the column names are automatically named F1, F2, Fn. Then it is just SELECT colname1, colname2, colname3 FROM ..... – Steve Feb 01 '17 at 08:08
  • Thanks sir steve for the information. it helped a lot. heres what i did: utos.CommandText = "SELECT [Column name1] From [" + sheetName + "]"; – Leynad Tabije Feb 01 '17 at 08:19
  • Is this question about ASP.NET or is it a WinForm/WPF app? – Steve Feb 01 '17 at 08:23
  • its a winform. whats the difference between asp.net and winform . sorry im new to this. – Leynad Tabije Feb 01 '17 at 08:26

1 Answers1

0

Create Bound fields in the frontend when you assign datasurce and bind it. The row with header ln will automatically bind with the first column and fn to second one. set Autogeneratecolumns="false" in datagridview.

       <asp:BoundField DataField="ln" HeaderText="LastName"/>
       <asp:BoundField DataField="fn" HeaderText="FirstName"/>
rexroxm
  • 868
  • 1
  • 9
  • 26
  • What make you think that this question is about ASP.NET? – Steve Feb 01 '17 at 08:22
  • Sorry my mistake, perhaps this might help. http://stackoverflow.com/questions/14793990/how-to-show-only-certain-columns-in-a-datagridview-with-custom-objects – rexroxm Feb 01 '17 at 08:27