質問

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?

役に立ちましたか?

解決

The column CS in the database can be null, so that you shouldn't use that reader to get int values. Use NullableDataReader instead to get the int? type. The use would be very similar:

stat.Cs = dr.GetNullableInt32("CS");

他のヒント

The value in your database in the CS column for that record is null. You can do one of two things: either fill in a value in the database, or modify your STATbatter class and set the Cs field to an int? instead of an int, which is a nullable class.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top