我编写了一个代码,允许用户将数据输入程序,然后转移到excel文件。但是当我的一个文本框为空时,我不希望添加任何内容。尽管我的if else条件,仍然添加了一行。我已经调试并使用了断点,即使txt_LRU是txt_LRU,txt_LRU!= null也是如此是否有空。有人可以告诉我为什么会这样吗?
private void button_kaydet_Click(object sender, EventArgs e){
//the text that is obtained from the text boxes and combo boxes.
string txt_LRU = this.txtbx_LRUno.Text.ToString();
string txt_yi = this.txtbx_yi.Text.ToString();
string txt_td = this.cmbx_td.Text.ToString();
string txt_toptarih = this.dtp_toplanti.Text.ToString();
string txt_bastarih = this.dtp_bas.Text.ToString();
string txt_teslimtarih = this.dtp_teslim.Text.ToString();
string txt_ilgilinot = this.txtbx_ilgiliNot.Text.ToString();
string txt_acikislem = this.txtbx_acikislem.Text.ToString();
string txt_referedosya = this.txtbx_referedosya.Text.ToString();
string txt_parcano = this.txtbx_parcano2.Text.ToString();
int lru_row = 0;
int kontrol = 0;
//if there is non existing LRU then save the data into a new row in excel
if (kontrol == 0)
{
if (txt_LRU != null || txt_LRU!="")
{
int x = satir_sayisi + 1;
string satir_no = x.ToString();
sheet1.Cells[1][satir_sayisi + 2] = satir_no;
sheet1.Cells[2][satir_sayisi + 2] = txt_LRU;
sheet1.Cells[3][satir_sayisi + 2] = txt_parcano;
sheet1.Cells[4][satir_sayisi + 2] = txt_yi;
sheet1.Cells[5][satir_sayisi + 2] = txt_acikislem;
sheet1.Cells[7][satir_sayisi + 2] = txt_td;
sheet1.Cells[8][satir_sayisi + 2] = txt_toptarih;
sheet1.Cells[9][satir_sayisi + 2] = txt_bastarih;
sheet1.Cells[10][satir_sayisi + 2] = txt_teslimtarih;
sheet1.Cells[11][satir_sayisi + 2] = txt_ilgilinot;
}
else if (txt_LRU == null || txt_LRU == "")
MessageBox.Show("Please add the LRU number ");
}
//to save and close the excel file
uyg.DisplayAlerts = false;
kitap.Save();
kitap.Close();
uyg.DisplayAlerts = true;
uyg.Quit();
DialogResult dialogResult2 = MessageBox.Show("Would you like to see the excel file?", "Bilgilendirme", MessageBoxButtons.YesNo);
if (dialogResult2 == DialogResult.Yes)
{
Process.Start(@"C:\\Users\\casperpc\\Desktop\\hey.xls");
}
else if (dialogResult2 == DialogResult.No)
{
}
}
答案 0 :(得分:2)
这种情况表明,当txt_LRU
不为空或非空时,您将执行操作。
当txt_LRU
null
不等于空字符串时。此案例符合OR
条件。
if (txt_LRU != null || txt_LRU!="")
{
/*row added*/
}
正确的条件是Not null AND not empty
:
if (txt_LRU != null && txt_LRU!="")
{
/*row added*/
}
PS:尝试使用string.IsNullOrWhiteSpace(txt_LRU)
答案 1 :(得分:1)
不适用于积分。
Null
与零长度字符串不同。一个简单的检查可以为您提供此信息。
上面的代码很简单:
private void button1_Click(object sender, EventArgs e)
{
string txt_string = this.textBox1.Text.ToString();
if (txt_string == null)
MessageBox.Show("Yes");
else
MessageBox.Show("No");
}
希望这有帮助。
答案 2 :(得分:0)
从文本框中读取时,您正在为txt_LRU分配值。但是,如果未初始化字符串,则字符串只能为null。这就是你收到真实的原因。
请参阅this explanation。