I have a MS Access database that has a table with several columns. When I click a button I want to take the rows of string data from one column of the database and display it in a rich text box. I have created the following code:
public static string DisplayListOfTeams()
{
//create a data table object to hold data retrieved from DB
DataSet ds = new DataSet();
//set SQL query to string variable
String sqlQuery = "SELECT * FROM Team";
//instantiate new OleDbDataAdapter object
OleDbDataAdapter adpTeams = new OleDbDataAdapter(sqlQuery, aConnection);
//add data in DB to the dataset object/table
adpTeams.Fill(ds, "TeamTable");
string myValue;
if (ds.Tables["TeamTable"].Rows.Count > 0)
{
//You must cast the value because it is an object
myValue = (string)ds.Tables["TeamTable"].Rows[0][0];
}
else
{
myValue = "No Data found";
}
return myValue;
}
richTextBox1.Text = TeamsDA.DisplayListOfTeams();
I receive an "Unable to cast object of type 'System.Int32' to type 'System.String'" error at the following line:
myValue = (string)ds.Tables["TeamTable"].Rows[0][0];
I'm not sure what I am doing wrong or how to go about doing what I am trying to do.
ds.Tables["TeamTable"].Rows[0][0]is int, so you can't cast to string. You can call.ToString()though...