输入字符串的格式不正确。 (可编辑的网格视图)

时间:2014-04-24 05:55:26

标签: c# asp.net gridview

每当我尝试编辑gridview中的信息时,它都会抛出这个错误....

这是我的行编辑代码

protected void GRDTech_RowEditing(object sender, GridViewEditEventArgs e)
{  
 GRDTech.EditRowStyle.BackColor = System.Drawing.Color.LightYellow;
 GRDTech.EditIndex = e.NewEditIndex;
 BindData();
}

这是我的代码:

 bool comparedResults = true;
TextBox txtAddFROMKMREAD = (TextBox)Default._def.GRDTech
    .FooterRow.FindControl("txtAddFROMKMREAD");
DropDownList drpPlateNum = (DropDownList)Default._def.GRDTech
    .FooterRow.FindControl("drpPlateNum");
string txt = txtAddFROMKMREAD.Text;
int readDepartureKM = Convert.ToInt32(txtAddFROMKMREAD.Text);

TextBox txtAddTOKMREADING = (TextBox)Default._def
    .GRDTech.FooterRow.FindControl("txtAddTOKMREADING");

int arrivalKMreading = Convert.ToInt32(txtAddTOKMREADING.Text);

comparedResults = (arrivalKMreading < readDepartureKM);

部分int readDepartureKM继续给我一个输入字符串不正确的错误。我该如何解决这个问题?

1 个答案:

答案 0 :(得分:0)

txtAddTOKMREADING.Text中的值似乎不是vlid integer(可能是空白的?)。

如果您不确定文字是否有效(例如,当您使用textbox来表示用户的输入时),最好使用int.TryParse

来自int.TryParse的文档:

  

将数字的字符串表示形式转换为32位有符号   整数当量。返回值表示是否转换   成功了。

int readDepartureKM ;
bool parsedSuccessfully = int.TryParse(txtAddFROMKMREAD.Text, out readDepartureKM )
if(parsedSuccessfully)
{
    //Do something with the value that is in readDepartureKM 
}
else
{
   //do something else (perhaps an error message?)
   string message =String.Format("'{0}' Is not a valid integer.",txtAddFROMKMREAD.Text);
}