Assign null to integer in C#

时间:2018-08-19 06:20:07

标签: c# .net winforms

I have a winforms application and i am trying to pass 5 parameters inside the tableadapter in order to execute a query but i get the error "Cannot convert from 'int?' to 'int'. All of them can be nulls.

private int? c_id ;
private string c_cn;
private int? c_afm;
private string c_job;
private string c_city;

private void btnView_Click(object sender, EventArgs e) {
c_id = (txtBox_id.Text != string.Empty) ? c_id = Convert.ToInt32(txtBox_id.Text) : c_id = null;
c_afm = (txtBox_afm.Text != string.Empty) ? c_afm = Convert.ToInt32(txtBox_afm.Text) : c_afm = null;
c_cn = (txtBox_cn.Text != string.Empty) ? c_cn = txtBox_cn.Text : c_cn = null;
c_job = (txtBox_job.Text != string.Empty) ? c_job = txtBox_job.Text : c_job = null;
c_city = (txtBox_job.Text != string.Empty) ? c_city = txtBox_city.Text : c_city = null;

this.clientBrowserTableAdapter.Fill(erpDataSet.PelatesBrowser,c_id,c_cn,c_afm, c_job,c_city);
}

The problem is at c_id and c_afm parameters. Any ideas?

2 个答案:

答案 0 :(得分:2)

您可以创建用于将字符串转换为int?

的专用方法
private int? ConvertToDbInt(string text)
{
    if (string.IsNullOrEmpty(text))
    {
        return null;
    }

    return int.Parse(text);
}

然后将其重用于不同的变量

c_id = ConvertToDbInt(txtBox_id.Text);
c_afm = ConvertToDbInt(txtBox_afm.Text);

您的实际问题是因为条件运算符?:期望正表达式和负表达式都产生相同类型的值,在您的情况下,它是int-表示正,而int?表示负

  

first_expression和second_expression 的类型都必须是   ,否则必须存在从一种类型到另一种类型的隐式转换。

如果您是条件运算符?:的忠实拥护者,那么只需确保两个表达式返回相同的类型,int?就您而言。

c_id = (txtBox_id.Text != string.Empty) ? (int?)Convert.ToInt32(txtBox_id.Text) : null;

当在行this.clientBrowserTableAdapter.Fill(...上引发异常时,这意味着Fill方法需要类型为int的参数,您可以通过调用.GetValueOrDefault()轻松地将可空int转换为int

this.clientBrowserTableAdapter.Fill(
    erpDataSet.PelatesBrowser,
    c_id.GetValueOrDefault(),
    c_cn,
    c_afm.GetValueOrDefault(), 
    c_job,
    c_city);

答案 1 :(得分:1)

I am a cow; cows say ,[object Object],. ,[object Object],. 预期为parts[i] = convertToStringOfHtml(<MyComponent key={i}>{parts[i]}</MyComponent>); 。您正在传递clientBrowserTableAdapter.Fill,它们不相同,并且没有隐式转换发生。您需要将其强制转换为int,即Nullable<int>或使用int的{​​{1}}属性。如果(int)c_id为null,那么您将不得不处理这种情况,否则在投射时会出现异常。

请注意,您的作业略有减少,您可以执行以下操作:

.Value