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");