0

Here's the code:

    protected void btnSearch_Click(object sender, EventArgs e)
{
    List<STATbatter> completelist = new List<STATbatter>();
    DALbatter batter = new DALbatter();
    batter.NameLast = txtLastName.Text;

    DataTable batters = DALbatter.getBattersByLastName(batter);

    for (int i = 0; i < batters.Rows.Count; i++)
    {
        DataRow bat = batters.Rows[i];

        STATbatter stat = new STATbatter();

        stat.PlayerID = bat.Field<String>("playerID");
        stat.G = bat.Field<Int32>("G");
        stat.Ab = bat.Field<Int32>("AB");
        stat.H = bat.Field<Int32>("H");
        stat.Bb = bat.Field<Int32>("BB");
        stat.Cs = bat.Field<Int32>("CS");
        stat.Doub = bat.Field<Int32>("2B");
        stat.Trip = bat.Field<Int32>("3B");
        stat.Hr = bat.Field<Int32>("HR");
        stat.Rbi = bat.Field<Int32>("RBI");
        stat.Sb = bat.Field<Int32>("SB");
        stat.K = bat.Field<Int32>("SO");
        stat.Ibb = bat.Field<Int32>("IBB");
        stat.Hbp = bat.Field<Int32>("HBP");
        stat.Sh = bat.Field<Int32>("SH");
        stat.Sf = bat.Field<Int32>("SF");
        stat.Gidp = bat.Field<Int32>("GIDP");

        //calculated fields
        stat.NameFull = STATbatter.fullName(bat.Field<String>("nameLast"), bat.Field<String>("nameFirst"));
        stat.Avg = STATbatter.battingAverage(stat.H, stat.Ab);
        stat.Obp = STATbatter.onBasePercentage(stat.Ab, stat.H, stat.Bb, stat.Hbp, stat.Sf);
        stat.Slg = STATbatter.slugging(stat.H, stat.Doub, stat.Trip, stat.Hr, stat.Ab);

        completelist.Add(stat);
    }

    gvBatters.DataSource = completelist;
    gvBatters.DataBind();
}

Here's the problem:

I attached an mdf file to the project in the App_Data file, created a connection string to use the local mdf. it was working just fine. I took the project to another PC, and on the line:

stat.Cs = bat.Field<Int32>("CS");

I get

Cannot cast DBNull.Value to type 'System.Int32'. Please use a nullable type.

not sure why this worked perfectly on the other PC, but nonetheless, how can I prevent this error?

4

2 回答 2

0

数据库中该记录的 CS 列中的值为空。您可以执行以下两种操作之一:在数据库中填写一个值,或者修改您的STATbatter类并将该Cs字段设置为 anint?而不是 an int,后者是一个可为空的 class

于 2013-05-08T20:54:06.480 回答
0

数据库中的 CS 列可以为空,因此您不应该使用该阅读器来获取int值。改用NullableDataReader来获取int?类型。用途将非常相似:

stat.Cs = dr.GetNullableInt32("CS");
于 2013-05-08T20:59:18.387 回答