Reputation: 13
I am running into the following problem. I don't know what i'm doing wrong. It shows me an error "The best overloaded method match for 'System.Data.Common.DbDataReader.GetString(int)' has some invalid arguments."
SqlDataReader myReader;
mycon.Open();
myReader = cmdDatabase.ExecuteReader();
while (myReader.Read())
{
string cName = myReader.GetString("C_Name");
textBox2.Text=cName;
}
Upvotes: 1
Views: 1700
Reputation: 22311
As has been mentioned several times now, the signature of GetString
requires an integer representing the column index. You can translate the column name to its ordinal position using GetOrdinal
.
Therefore, you can get the string value of the "C_NAME"
column by using myReader.GetString(myReader.GetOrdinal("C_NAME"))
.
SqlDataReader
also overrides the indexer, which lets you write the same as (string)myReader["C_Name"]
Complete example:
var sqc = new SqlCommand("SELECT C_NAME from table", con);
using (var reader = sqc.ExecuteReader())
{
while (reader.Read())
{
int ordinal = reader.GetOrdinal("C_NAME");
string byOrdinal = reader.GetString(ordinal);
string byIndexer = (string)reader["C_NAME"];
Console.Writeline("Column {0}, has the value of {1} (which is the same as {2})",
ordinal, byOrdinal, byIndexer);
}
}
You should also be careful to wrap your readers in using
statements to ensure you don't leak database connections or run into a case where you consider enabling MARS.
Upvotes: 2
Reputation: 66511
The GetString
method only accepts an int
. You're passing it a string
.
From MSDN, the parameter (an integer) represents "the zero-based column ordinal."
If C_Name
is the first column (for example), you'd want to call:
string cName = myReader.GetString(0);
Upvotes: 3
Reputation: 10456
As the error indicates, you are trying to use an overload of the GetString
which does not exist.
You are passing a string
argument, while the method is expecting an integer
that represents the index of the requested column.
You can read more about the method in the dcumetnation
Try changing your code to something like:
int indexOf cNameIdx = 5;// replace this with the real index from your select query
string cName = myReader.GetString(cNameIdx );
Upvotes: 1
Reputation: 300827
Look at the signature of GetString()
:
System.Data.Common.DbDataReader.GetString(int)
It takes an integer ordinal (i.e. zero-based position) and you are trying to pass a string. There are no overloads which take a single string parameter.
Upvotes: 1