michael_hk
Well-known member
Hi,
I use the following code to read data from excel file
I have defined two areas (Course and Student) in excel and want to loop throught the datatable student to check what subjects he/she has enrolled. But in the second foreach loop, oRow[oColumn.ColumnName].ToString() sometimes gives me empty string (I am sure the value is 1 in the excel file) and sometimes gives 1 (correct value). The programme output is totally unpredictable...
Is there anything I am doing wrong here?
Thanks.
Michael
I use the following code to read data from excel file
Code:
private void btnProcess_Click(object sender, System.EventArgs e)
{
... // variable declarations
OleDbConnection conn = new OleDbConnection(); // connect to the file
conn.ConnectionString = strConn;
conn.Open();
OleDbDataAdapter adapter = new OleDbDataAdapter("SELECT * FROM Course", conn); // get courses info
DataSet ds = new DataSet();
adapter.Fill(ds, "course");
OleDbDataAdapter adapter2 = new OleDbDataAdapter("SELECT * FROM Student", conn); // get students info
adapter2.Fill(ds, "student");
foreach(DataRow oRow in ds.Tables["course"].Rows) // store courses info in array
{
i = 6; // skip first 6 elements, match the index below
foreach (DataColumn oColumn in ds.Tables["course"].Columns)
{
subject[i] = oRow[oColumn.ColumnName].ToString();
i++;
}
}
foreach(DataRow oRow in ds.Tables["student"].Rows)
{
i = 0;
foreach (DataColumn oColumn in ds.Tables["student"].Columns)
{
if ( i>=6 ) // course info start from Cell7
{
if ( oRow[oColumn.ColumnName].ToString() == "1") // [COLOR=DarkRed]PROBLEM HERE[/COLOR]
{
subSelected += subject[i] + Environment.NewLine; // subSelected stores the subjects selected
}
}
i++;
}
}
...
}
I have defined two areas (Course and Student) in excel and want to loop throught the datatable student to check what subjects he/she has enrolled. But in the second foreach loop, oRow[oColumn.ColumnName].ToString() sometimes gives me empty string (I am sure the value is 1 in the excel file) and sometimes gives 1 (correct value). The programme output is totally unpredictable...
Is there anything I am doing wrong here?
Thanks.
Michael
Last edited by a moderator: