Reputation: 7
I have the following code:
void combofill()
{
String str = "server=RAVI;database=sampledb;Integrated Security=SSPI";
String query = "select * from DentalLogin";
SqlConnection con = new SqlConnection(str);
SqlCommand cmd = new SqlCommand(query, con);
SqlDataReader dr;
try
{
con.Open();
dr = cmd.ExecuteReader();
while(dr.Read())
{
string ut = dr.GetString("usertype");
ComboBoxut.Items.Add(ut);
}
}
I am getting error at string ut=dr.GetString("usertype");
The error is:
Cannot convert string to int
Upvotes: 0
Views: 41
Reputation: 5957
Instead of using GetString
method, you can below code to get the column value in string:
while(dr.Read())
{
string ut=dr["usertype"].ToString();
//..........
}
Upvotes: 0
Reputation: 223267
GetString
expects an integer value for column ordinal, You are passing it a string, probably a column name. Specify the correct column ordinal or use:
string ut = Convert.ToString(dr["usertype"]);
Or if you want to use GetString
then specify the column ordinal like:
string ut = dr.GetString(0); //assuming 0 ordinal is for `usertype`
One more thing to add, enclosing your SqlConnection
, SqlCommand
and SqlDataReader
in using statements. This will ensure their disposal after usage.
Upvotes: 2