[英]Convert Textbox value to int and also check for is it Empty or Not
當我輸入到文本框(tAge)時,我試圖更新 gridview 中一個人的記錄,它顯示一個異常輸入字符串的格式不正確。 我已經嘗試了很多代碼,但無法正常工作,請幫助我。在此先感謝。 這是我更新人員詳細信息的代碼
protected void UpdateRecord(object sender, GridViewUpdateEventArgs e)
{
int personID = Int32.Parse(GridView1.DataKeys[e.RowIndex].Value.ToString());
int intResult = 0;
GridViewRow row = GridView1.Rows[e.RowIndex];
TextBox tFN = (TextBox)row.FindControl("txtFName");
TextBox tLN = (TextBox)row.FindControl("txtLName");
TextBox tAge = (TextBox)row.FindControl("txtAge");
// instantiate BAL
PersonBAL pBAL = new PersonBAL();
PersonBO person = new PersonBO();
try
{
person.PersonID = personID;
person.FirstName = tFN.Text;
person.LastName = tLN.Text;
person.Age = Int32.Parse(tAge.Text);
//if (String.IsNullOrEmpty(String.Trim(tFN.Text)))
if (tFN.Text.Trim() == "")
{
lblMessage.Text = "Name can't be Blank";
}
else if (tLN.Text.Trim() == "")
{
lblMessage.Text = "LastName can't be Blank";
}
else if (tAge.Text.Trim()=="")
{
lblMessage.Text = "Age can't be Blank";
}
else
{
intResult = pBAL.Update(person);
if (intResult > 0 && tFN.Text != "")
{
string message = "Updated Successfully!";
string script = "window.onload = function(){ alert('";
script += message;
script += "');";
script += "window.location = '";
script += Request.Url.AbsoluteUri;
script += "'; }";
ClientScript.RegisterStartupScript(this.GetType(), "SuccessMessage", script, true);
}
//else if( tFN.Text == "")
//{
//}
else
{
string message = "Already Exist!";
string script = "window.onload = function(){ alert('";
script += message;
script += "');";
script += "window.location = '";
script += Request.Url.AbsoluteUri;
script += "'; }";
ClientScript.RegisterStartupScript(this.GetType(), "SuccessMessage", script, true);
//lblMessage.Text = message.ToString();
}
}
}
catch (Exception ee)
{
lblMessage.Text = ee.Message.ToString();
}
finally
{
person = null;
pBAL = null;
}
GridView1.EditIndex = -1;
// Refresh the list
BindGrid();
}
我建議先檢查Text
屬性,然后再將其分配給適當的值。 對於轉換,存在一個很好的方法TryParse
它返回一個bool
並且僅在格式正確時才進行解析。
try
{
// ask whether it is blank or full of spaces
if (string.IsNullOrWhiteSpace(tFN.Text))
{
lblMessage.Text = "Name can't be Blank";
}
else
{
person.FirstName = tFN.Text;
}
// do the same again for the last name
if (string.IsNullOrWhiteSpace(tLN.Text))
{
lblMessage.Text = "Name can't be Blank";
}
else
{
person.FirstName = tLN.Text;
}
// use TryParse for the age
int p_age;
if (Int.TryParse(tAge.Text, out p_age))
{
person.Age = p_age;
}
else
{
lblMessage.Text = "Age is in incorrect Format";
}
....
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.