SQL Server Express and C# : Database Charting

I am trying to link my SQL Server Express database to a chart in ac# application. I am trying to extract the age of some employees to display them in a bar char. Here is my code

string constring = "Data Source=.SQLEXPRESS;AttachDbFilename=C:UsersMichaelDownloadsEmployeeEmployeeEmployeeEmployeeDetails.mdf;Integrated Security=True;User Instance=True;Initial Catalog=Employee";

SqlConnection conDatabase = new SqlConnection(constring);
SqlCommand cmdDatabase = new SqlCommand("Select * from Employee;", conDatabase);
SqlDataReader myReader;

try{
    conDatabase.Open();
    myReader=cmdDatabase.ExecuteReader();

    while(myReader.Read())
    {
        this.chart1.Series["Age"].Points.AddXY(myReader.GetString("FirstName"), myReader.GetInt32("Age"));
    }
}

When I compile my program, I get 4 error messages, which relate to this line:

(myReader.GetString("FirstName"), myReader.GetInt32("Age"))

The error messages are:

The best overloaded method match for 'System.Data.Common.DbDataReader.GetString(int)' has some invalid arguments
Argument 1: cannot convert from 'string' to 'int' The best overloaded method match for 'System.Data.Common.DbDataReader.GetInt32(int)' has some invalid arguments
Argument 1: cannot convert from 'string' to 'int'

The SQL Server Express database uses VARCHAR for FirstName and INT for Age

what have i done wrong?


IDataReader 's .Get* methods only take the index of the column to be accessed, not the column name.

So instead of

myReader.GetString("FirstName")

You'll need something like

myReader["FirstName"].ToString()

and

Convert.ToInt32(myReader.GetInt32("Age")))

If you are doing this in a tight loop, then you can cache the name : index mappings.


Error 1 The best overloaded method match for 'System.Data.Common.DbDataReader.GetString(int)' has some invalid arguments

DbDataReader.GetString method takes argument as an int , not string .

Gets the value of the specified column as an instance of String.

public abstract string GetString(
    int ordinal
)

Use this method with what is the zero-based column ordinal of your FirstName and Age columns.

Error 2 Argument 1: cannot convert from 'string' to 'int'

There is no implicit conversation from string to int . You get this error actually because myReader.GetString("FirstName") method returns string but your AddXY() method probably except int as a first parameter.


您应该使用GetString(0)或GetString(1)或GetString(2)

链接地址: http://www.djcxy.com/p/15894.html

上一篇: 装配使用变量

下一篇: SQL Server Express和C#:数据库图表