终于解决这个数据源参数转换的问题。
假设表test是有字段a nvarchar(50) , b decimal, c datetime, d bool
在winform中建立一个数据源。在数据源中添加一个插入数据的方法insertData(string a,decimal b,datetime c,bool d),
一直为这不是字符串的数据类型的转换为难。
如在frm1中有四个文本框 分别输入内容。再用一个按钮调用insertData方法。如果其中的文本框为空或者内容转换出错,存入数据库的数据就库空。当然如果输入的内容不能转换,就应该有提示。这只是个假设,在不输入内容就为空是常见的。
怎样处理这种转换呢?
今天发现一个 System.Nullable<T> 的类。能在转换成各种类型,并同时能为null.
部分代码如下。
demotestDataSetTableAdapters.t_testTableAdapter testAdapter
=
new
ErrorData.demotestDataSetTableAdapters.t_testTableAdapter();
string a = textBox1.Text;
System.Nullable < decimal > b;
System.Nullable < DateTime > c;
System.Nullable < bool > d;
try
... {
b = Convert.ToDecimal(textBox2.Text);
}
catch (Exception eb)
... {
b = null;
}
try
... {
c = Convert.ToDateTime(textBox3.Text);
}
catch (Exception ec)
... {
c = null;
}
try
... {
d = Convert.ToBoolean(textBox4.Text);
}
catch (Exception ed)
... {
d = null;
}
textBox1.Text = testAdapter.InsertData(a, b, c, d).ToString();
string a = textBox1.Text;
System.Nullable < decimal > b;
System.Nullable < DateTime > c;
System.Nullable < bool > d;
try
... {
b = Convert.ToDecimal(textBox2.Text);
}
catch (Exception eb)
... {
b = null;
}
try
... {
c = Convert.ToDateTime(textBox3.Text);
}
catch (Exception ec)
... {
c = null;
}
try
... {
d = Convert.ToBoolean(textBox4.Text);
}
catch (Exception ed)
... {
d = null;
}
textBox1.Text = testAdapter.InsertData(a, b, c, d).ToString();