Reputation: 1620
When I am Passing the Value of the selected in the Gridview for deletion it throws Input String was not in correct format exception My Code is,
protected void gridview1_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName.ToUpper().ToString() == "DELETEREC")
{
try
{
ViewState["id"] = e.CommandArgument.ToString().Trim();
int r = Namespace.SPs.StoredProcedure(Convert.ToInt32(ViewState["id"])).Execute();//Exception thrown Here
if (r > 0)
{
ClientMessaging("Record Deleted Successfully");
Clear();
fillgrid();
}
}
catch (SqlException ex)
{
ClientMessaging(ex.Message);
}
}
}
Kindly help me out in this
My SP Method is,
public static StoredProcedure StoredProcedure(int id)
{
SubSonic.StoredProcedure sp = new SubSonic.StoredProcedure("StoredProcedure", DataService.GetInstance("TEST"), "");
sp.Command.AddParameter("@Id", id, DbType.Int32);
return sp;
}
Upvotes: 1
Views: 2126
Reputation: 216343
if the e.CommandArgument
is an empty string you get that kind of exception at the Convert.ToInt32(ViewState["id"])
I will try to changing your code in this way
try
{
int resultID;
if(Int32.TryParse(e.CommandArgument.ToString().Trim(), out resultID))
{
ViewState["id"] = e.CommandArgument.ToString().Trim();
.....
}
else
// handle the case of not an integer value
UPDATE Seeing the code of StoredProcedure and with the above code in place then the next reason for the failure is in the StoredProcedure that expects a different type of parameter (For example a NVARCHAR instead of an INT)
Upvotes: 1
Reputation: 63105
If you using Command Argument to get the ID you need to set it as command argument in the gridview like CommandArgument='<%#Eval("ID")%>'
Or else you can use DaTaKey to Get ID field as below
<asp:gridview id="gridview1" runat="server" datakeynames="ID"
..... >
</asp:gridview>
then in Row Command
protected void gridview1_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName.ToUpper().ToString() == "DELETEREC")
{
try
{
int index = gridview1.SelectedIndex;
int ID = Convert.ToInt32(gridview1.DataKeys[index].Value.ToString());
int r = Namespace.SPs.StoredProcedure(ID ).Execute();
// do stuff
}
catch (SqlException ex)
{
ClientMessaging(ex.Message);
}
}
}
Upvotes: 1