Your line of code:
string row = data_table.Rows["Name"][ID].toString();
causes the error "cannot convert from string to integer" because a DataTable's .Rows
collection expects an integer index, and you passed a string ("Name")
In other words think of datatable.Rows
as an array - you have to index it with a number, not a string. Because you passed a string and it cannot be automatically converted to a number you get a "cannot convert" error
As an example to access the first row you would data_table.Rows[0]
, for the 10th row it would be .Rows[9]
To retrieve the name of the first person in the table:
string name = data_table.Rows[0]["Name"].ToString();
Your code has other issues:
toString();
needs a capital T
- You don't make any attempt to use the parameters passed in to refine the search, so your query downloads all the rows from the DB. Perhaps it should have looked like:
public static string SelectNameFromId(OleDbConnection connection, int id)
{
DataTable data_table = new DataTable();
OleDbDataAdapter adapter = new OleDbDataAdapter("SELECT Name FROM Student WHERE ID = ?", connection);
adapter.SelectCommand.Parameters.AddWithValue("p1", id); //positional indexing
adapter.Fill(data_table);
string n = data_table.Rows[0]["Name"].ToString();
return n;
}