简体   繁体   中英

Get Excel Row Number using C#

I want to get row number of my excel data. Here, I have excel file that has data like below.

I have data :

WSID  Nominal
123   1000
456   2000
789   3000
987   4000
654   5000
321   6000

I want to show row number of my data that is shown in DatagRidView. How can I do that ?

string koneksi = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=D:\Program-Pengisian-Uang-ATM-BCA-SOY\Program-Pengisian-Uang-ATM-BCA-SOY\bin\x86\Debug\ATM SLA Surabaya.xlsx; Extended Properties='Excel 12.0 xml;HDR=YES;'";

    private void PrintScheduleBtn_Click(object sender, EventArgs e)
    {
    Excel.Application oApp;
    Excel.Worksheet oSheetCartridge;
    Excel.Workbook oBook;

    oApp = new Excel.Application();
    oApp.Visible = true;
    oApp.DisplayAlerts = false;

    oBook = oApp.Workbooks.Open(lokasifile, 0, false, 5, "", "", false, Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, "", true, false, 0, true, false, false);
    oSheetCartridge = oBook.Sheets["Cartridge"];

    OleDbConnection kon2 = new OleDbConnection(koneksi); //database
    OleDbCommand comm = kon2.CreateCommand();

    foreach (DataGridViewRow row in JadwalisiGV.Rows)
    {
        if (!row.IsNewRow)
        {
        kon2.Open();    
        comm.CommandText = "SELECT * FROM [Data$] WHERE [WSID] = '"+ row.Cells["WSID"].Value +"'";
        listBox1.Items.Add(); // I want to show row number of my WSID data that is shown in JadwalisiGV here
        kon2.Close();

        }
    }

    } 

You can try this code

foreach (DataGridViewRow row in JadwalisiGV.Rows)
    {
        if (!row.IsNewRow)
        {
        kon2.Open();    
        comm.CommandText = "SELECT WSID, Nominal,ROW_NUMBER() over (order by WSID) FROM [Data$] WHERE [WSID] = '"+ row.Cells["WSID"].Value +"'";
        row.HeaderCell.Value = (row.Index + 1).ToString();
        listBox1.Items.Add(); // I want to show row number of my WSID data that is shown in JadwalisiGV here
        kon2.Close();

        }
    }

Try like this:

  foreach (DataGridViewRow row in JadwalisiGV.Rows)
    {.
     .
      int index = JadwalisiGV.Rows.IndexOf(row);
     .
     .
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM