将datagridview中的单元格更改为空值

时间:2013-08-08 09:33:35

标签: c# datagridview

我有更改datagridView中单元格的方法,并且当我重写text(String)时工作正常 但我希望例如重写电子邮件到空值,我不知道这是怎么做的。
我只能将电子邮件重写为另一封电子邮件(字符串到另一个字符串)

我改变细胞的方法是:

public void ChangeCellEmail(int col, string[] emails)
    {


        string sep = ";";
        string text = "";

        foreach (DataGridViewCell cell in dataGridView1.SelectedCells)
        {


            for (int i = 0; i < emails.Length ;i++)
            {

                if (emails[i].ToString().Trim() != "")
                {


                    text = text + emails[i] + sep ;
                    dataGridView1.Rows[cell.RowIndex].Cells[col].Value = text;
                }
            }

        }

    }

我方法的调用代码是

            string mail = txtBox1.Text;
            string mail1 = txtBox2.Text;
            string mail2 = txtBox3.Text;
            string mail3 = txtBox4.Text;
            string mail4 = txtBox5.Text;

            string[] mails = new string[] { mail, mail1, mail2, mail3, mail4 };


            frm1.ChangeCellEmail(2, mails);
            this.Dispose();

感谢您的帮助。

2 个答案:

答案 0 :(得分:1)

使用以下代码,我可以传递5个完整的电子邮件地址,其中部分/全部可能为“空”,tempVar将始终包含正确的数据。

public Form1()
    {
        InitializeComponent();

        const string mail = "First";
        const string mail1 = "Second";
        const string mail2 = "Third";
        const string mail3 = "";
        const string mail4 = "Fifth";

        var mails = new string[] { mail, mail1, mail2, mail3, mail4 };

        ChangeCellEmail(2, mails);
    }


    public void ChangeCellEmail(int col, string[] emails)
    {
        var sep = ";";
        var text = "";
        var tempVar = ""; //New temp variable (representing your dataGrid.value)

        for (int emailList = 1; emailList < 5; emailList++)
        {
            for (var i = 0; i < emails.Length; i++)
            {

                if (emails[i].Trim() != "")
                {
                    text = text + emails[i] + sep;
                    tempVar = text;
                }
                else
                {
                    tempVar = string.Empty;
                }
            }

        }

    }

检查每个循环上的tempVar,你会看到我指的是什么。

答案 1 :(得分:0)

以下是建议的解决方案:

public void ChangeCellEmail(int emailColumnIndex, string[] emails)
{
  var emailsAsCsv = string.Join(";", emails.Where(e => !string.IsNullOrWhiteSpace(e)));
  foreach (DataGridViewCell cell in dataGridView1.SelectedCells)
  {
    dataGridView1.Rows[cell.RowIndex].Cells[emailColumnIndex].Value = emailsAsCsv;
  }
}

这会使用以分号分隔的非空电子邮件列表更新所选单元格的Email列。

用法:

var emailColumnIndex = 2; // The third column in the DataGridView (zero-indexed)
var emails = new[] {txtBox1.Text, txtBox2.Text, txtBox3.Text, txtBox4.Text, txtBox5.Text};
ChangeCellEmail(emailColumnIndex, emails);

希望这有帮助。