the*_*van 18 c# asp.net user-controls types
我有一个带有Integer DataType的One ColumnName"CustomerID"的数据表.动态地我想向DataTable添加行.为此,我创建了一个DataRow对象,如:
DataTable dt = new DataTable();
DataRow DR = dt.NewRow();
DR["CustomerID"] = Convert.ToInt32(TextBox1.Text);
Run Code Online (Sandbox Code Playgroud)
但是如果TextBox包含空字符串,则会抛出错误.在这种情况下,我想将Null值分配给CustomerID.这该怎么做?
Mar*_*ell 27
空/空字符串的格式错误; 你需要检测那个场景并补偿:
DR["CustomerID"] = string.IsNullOrWhiteSpace(text)
? DBNull.Value : (object)Convert.ToInt32(text);
Run Code Online (Sandbox Code Playgroud)
DR["CustomerID"] = !string.IsNullOrEmpty(TextBox1.Text)
? Convert.ToInt32(TextBox1.Text)
: DBNull.Value;
Run Code Online (Sandbox Code Playgroud)
但您还应该检查该值是否是有效的整数:
int value;
if(int.TryParse(TextBox1.Text, out value))
{
DR["CustomerID"] = value;
}
else
{
DR["CustomerID"] = DBNull.Value;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
67517 次 |
| 最近记录: |