c_sharpkid

c_sharpkid

  • NA
  • 29
  • 0

Spcified cast is not valid - Exception

May 22 2004 9:28 PM
In my webpage, I have an datagrid, 2 textboxes and an update button. When user clicks the edit button in the button column of the datagrid, row data comes in textboxes and user can update the data. My problem is when I click the update button after changing the data in textbox, I get "Specified Cast is not Valid" exception. Here is my code .. SqlConnection cn; SqlDataAdapter da ; SqlCommand cmd ; string strsql ; DataSet ds ; private void Page_Load(object sender, System.EventArgs e) { cn = new SqlConnection ("Data Source=*********;uid=sa;database=northwind;"); if(!Page.IsPostBack) { BindData(); } } void BindData() { DataGrid1.DataSource = GetData("Select * from Region"); DataGrid1.DataBind(); } DataSet GetData(string strSql) { da = new SqlDataAdapter(strSql, cn); ds = new DataSet(); da.Fill(ds); return ds; } protected void ItemCommand(Object source,System.Web.UI.WebControls.DataGridCommandEventArgs e) { if (e.CommandName == "Add code") { //'Fill the Textboxes with relevant data FillTheData(e.Item.Cells[1].Text, e.Item.Cells[2].Text); lblMessage.Text=""; } } void FillTheData(string RegionID,string RegionDescription) { txtRegionID.Text = RegionID; txtRegionDescription.Text = RegionDescription; } private void btnUpdate_Click(object sender, System.EventArgs e) { try { strsql = "Update Region set RegionDescription=@RegionDescription where RegionId=@RegionId"; cmd = new SqlCommand(strsql, cn); cmd.Parameters.Add(new SqlParameter("@RegionId", SqlDbType.Int)); cmd.Parameters.Add(new SqlParameter("@RegionDescription", SqlDbType.NVarChar, 40)); cmd.Parameters["@RegionId"].Value = Convert.ToInt32(txtRegionID.Text); cmd.Parameters["@RegionDescription"].Value = txtRegionDescription.Text; cn.Open(); cmd.ExecuteNonQuery(); BindData(); lblMessage.Text = "Updated Successfully"; } catch (Exception ex) { lblMessage.Text = ex.Message; /* lblMessage.ForeColor = Color.Red;*/ } finally { cn.Close(); } } I think error is somewhere in ItemCommand function or btn_updateclick..... I have read so many article on internet but none of them specified a remedy Thank you C_sharpkid

Answers (3)