I currently have a Gridview that is populated through the selection of a value from the drop down list. Once the value is selected the gridview is populated and I am trying to allow the user to edit values in the gridview using 'RowUpdating' event. However I am trying to update the values in the Gridivew based on the value from the Drop Down list which is 'StockTakeIDNew'.
Here is my c# code.
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
try
{
using (SqlConnection sqlCon = new SqlConnection(@"Data Source=(local)\;Initial Catalog=SmallBatch;Integrated Security=True;"))
{
sqlCon.Open();
string query = "UPDATE Stock_Take_Item SET BarQuantity=@BarQuantity, StorageQuantity=@StorageQuantity WHERE StockTakeIDNew =@id";
SqlCommand sqlCmd = new SqlCommand(query, sqlCon);
sqlCmd.Parameters.AddWithValue("@BarQuantity", (GridView1.Rows[e.RowIndex].FindControl("barQuantityTxt") as TextBox).Text.Trim());
sqlCmd.Parameters.AddWithValue("@StorageQuantity", (GridView1.Rows[e.RowIndex].FindControl("storageQuantityTxt") as TextBox).Text.Trim());
sqlCmd.Parameters.AddWithValue("@id", Convert.ToInt32(GridView1.DataKeys[e.RowIndex].Value.ToString()));
sqlCmd.ExecuteNonQuery();
String query1 = "SELECT Stock_Take.Username, Item.ItemID, Item.ItemDesc, Stock_Take_Item.BarQuantity, Stock_Take_Item.StorageQuantity, Stock_Take.StockTakeIDNew FROM Item INNER JOIN Stock_Take_Item ON Item.ItemID = Stock_Take_Item.ItemID INNER JOIN Stock_Take ON Stock_Take_Item.StockTakeIDNew = Stock_Take.StockTakeIDNew where Stock_Take.StockTakeIDNew = @DATE";
SqlConnection con = new SqlConnection(@"Data Source=(local)\;Initial Catalog=SmallBatch;Integrated Security=True;");
con.Open();
SqlCommand cmd = new SqlCommand(query1, con);
DdlUser.SelectedValue.GetType();
cmd.Parameters.Add("@DATE", SqlDbType.Int).Value = DdlUser.SelectedValue;
SqlDataReader reader = cmd.ExecuteReader();
GridView1.DataSource = reader;
GridView1.DataBind();
}
}
I am using this code. I basically don't the @ID value to be .DataKeys and instead the value of the SelectedIndexChanged from the DDL.
The code runs except i get the error: Index was out of range. Must be non-negative and less than the size of the collection. Parameter name: index