Reputation: 4662
I am querying an access database to get a quantity. Here's my code:
this.inventoryTableAdapter.Fill(this.garysInventoryDataSet.Inventory);
CurrentRow = (from x in garysInventoryDataSet.Inventory
where x.InventoryId == InventoryId
select x).FirstOrDefault();
if (CurrentRow == null)
{
MessageBox.Show("Inventory Item Not Found.");
}
yearToDateQuantityTextBox.Text = CurrentRow["YearToDateQuantity"].ToString();
When the user clicks a button, I want to increment this number by 1:
private void button3_Click(object sender, EventArgs e)
{
CurrentRow["YearToDateQuantity"]++;
}
The CurrentRow line is being cast as an object and won't let me add to it directly. Can I somehow safely cast this to an int so that I can add to it?
What's the proper way to handle this?
Upvotes: 1
Views: 23
Reputation: 7213
You can use as
operator:
int? count = CurrentRow["YearToDateQuantity"] as int?;
CurrentRow["YearToDateQuantity"] = count + 1; //null + 1 is null
Or just:
CurrentRow["YearToDateQuantity"] = (CurrentRow["YearToDateQuantity"] as int?) + 1; //null + 1 is null
Upvotes: 0
Reputation: 13146
As you said, you can't increment an object like that;
CurrentRow["YearToDateQuantity"]++;
You should cast to int and increment it;
CurrentRow["YearToDateQuantity"] = Convert.ToInt32(CurrentRow["YearToDateQuantity"]) + 1;
Upvotes: 1