使用C#添加到excel文件

我写了一个代码,允许用户input数据到程序中,这将转移到一个excel文件。 然而,我不希望任何东西被添加时,我的文本框之一是empty.With这个代码行仍然被添加,尽pipe我的if else条件。我debugging和使用的断点和txt_LRU!= null是真实的,即使txt_LRU是空了还是不行。请有人告诉我为什么会发生这种情况?

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) { } } 

这种情况说,当你的txt_LRU不为空或者不为空时,你会做些什么。 当txt_LRUnull不等于一个空string。 这种情况符合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)

不适用于积分。

Null与零长度string不同。 一个简单的检查可以给你这个信息。

在这里输入图像说明

上面的代码很简单:

 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"); } 

希望这可以帮助。

当您从文本框中读取时,您正在为txt_LRU分配一个值。 但是,string只有在未初始化的情况下才能为空。 这就是为什么你收到真实。

看到这个解释 。