簡體   English   中英

DataGridView到Windows Forms C#上的文本文件

[英]DataGridView to text file on Windows Forms C#

我有一個要寫入文本文件的datagridview。 這是我的代碼:

private void WriteToFile_Click(object sender, EventArgs e)
{
    StreamWriter sW = new StreamWriter("list.txt");
    for (int i = 0; i < 6; i++)
    {
        string lines = "";
        for (int col = 0; col < 6; col++)
        {
            lines += (string.IsNullOrEmpty(lines) ? " " : ", ") + 
                dataGridView.Rows[i].Cells[col].Value.ToString();
        }
        sW.WriteLine(lines);
        sW.Close();
    }
}

當我單擊按鈕時,它給我一個錯誤:

System.NullReferenceException

喬,

嘗試為每個循環使用a:

StreamWriter sW = new StreamWriter("list.txt");
foreach (DataGridViewRow r in dataGridView.Rows) {
    string lines = "";
    foreach (DataGridViewCell c in r.Cells) {
        lines += (string.IsNullOrEmpty(lines) ? " " : ", ") + dataGridView.Rows[i].Cells[col].Value == null ? string.Empty : dataGridView.Rows[i].Cells[col].Value;
    }

    sW.WriteLine(lines);
}

網格中的一個或多個值為null ,或者換句話說,為“ nothing”。 因此,當您使用訪問dataGridView.Rows[i].Cells[col].Value屬性,然后將其轉換為字符串時,您嘗試將null為字符串,然后引發異常。 您應該檢查空值,如下所示:

(如果您使用的是.net 4.6)

lines += (string.IsNullOrEmpty(lines) ? " " : ", ") + dataGridView.Rows[i].Cells[col].Value?.ToString();

注意“ Value之后的額外問號

(如果您使用的是較舊的.net)

lines += (string.IsNullOrEmpty(lines) ? " " : ", ") + dataGridView.Rows[i].Cells[col].Value == null ? string.Empty : dataGridView.Rows[i].Cells[col].Value;

希望這可以幫助。

編輯:由於您正在獲取System.ArgumentOutOfRangeException ,請確保您沒有超出網格的范圍-嘗試訪問許多行或列。 為確保您處於約束中,請使用

for (int i = 0; i < dataGridView.RowCount; i++)

對於您的第一個循環,

for (int col = 0; col < dataGridView.ColumnCount; col++)

第二

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM