[英]change cell in datagridview to empty value
我有更改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();
謝謝你們的幫助。
使用以下代碼,我可以傳入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,您將看到我指的是什么。
這是一個建議的解決方案:
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);
希望這可以幫助。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.