I am trying to get value from excel's cell to textbox in c#. I have used dataset to get the value from excel , but when taking value from dataset to text box it give error
There is no no row at position 0
I also tried using Item Array but no use . Heres my code:
DataSet dsloc = new DataSet();
OleDbDataAdapter daloc = new OleDbDataAdapter();
string connStr = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + txtfilepath.Text + ";Extended Properties=\"Excel 8.0;HDR=Yes;\";";
OleDbConnection con = new OleDbConnection(connStr);
string strloc = "select * from [sheet1$A5:A5]";
OleDbCommand cmdloc = new OleDbCommand(strloc, con);
con.Open();
dsloc.Clear();
daloc.SelectCommand = cmdloc;
daloc.Fill(dsloc);
txtloc.Text = dsloc.Tables[0].Rows[0]["Location"].ToString();
I have tried
DataRow drow;
drow = dsloc.Tables[0].Rows[0];
txtloc.Text = drow.ItemArray.GetValue(1).ToString();
Also
txtloc.Text = dsloc.Tables[0].Rows[0][0].ToString();
My dataset shows there is value in it.
But none of these work. Please advise. Thanks
Figured out the solution, the value coming from excel was actually the name of the column of the datatable as one can see on my screenshot, so I just need to get the column name.
DataTable dtloc = new DataTable();
string connStr = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + txtfilepath.Text + ";Extended Properties=\"Excel 8.0;HDR=Yes;\";";
string strloc = "select * from [sheet1$A5:A5]";
OleDbCommand cmdloc = new OleDbCommand(strloc, con);
con.Open();
daloc.SelectCommand = cmdloc;
string location = dtloc.Columns[0].ColumnName.ToString();
also used datatable instead of dataset.
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.