DataGridView打印

时间:2011-08-22 04:36:52

标签: c# printing datagridview export

如何从DataGridView中将指定的行打印到文件中? 另外我如何打印出某些列?

这就是我一直在尝试使用的......但它无法正常工作..:

    private void saveButton_Click(object sender, EventArgs e)
    {
            saveFile1.DefaultExt = "*.txt";
            saveFile1.Filter = ".txt Files|*.txt|All Files (*.*)|*.*";
            saveFile1.RestoreDirectory = true;

            if (saveFile1.ShowDialog() == DialogResult.OK)
            {
                StreamWriter sw = new StreamWriter(saveFile1.FileName);

                List<string> theList = new List<string>();

                foreach (var line in theFinalDGV.Rows)
                {
                    if (line.ToString().Contains("FUJI"))
                        richTextBox1.AppendText(line + "\n");
                }
            }
    }

任何人都可以帮助我朝正确的方向发展吗?

1 个答案:

答案 0 :(得分:0)

DataGridViewRow.ToString()仅返回返回的typename,而不是行内容。您可以使用此扩展程序获取rowcontent('ColumnName'):

public static class Extender {
    public static string RowToString(this DataGridViewRow dgvr) {
        string output = "";

        DataGridView dgv = dgvr.DataGridView;

        foreach (DataGridViewCell cell in dgvr.Cells) {

            DataGridViewColumn col = cell.OwningColumn;
            output += col.HeaderText + ":" + cell.Value.ToString() + ((dgv.Columns.IndexOf(col) < dgv.Columns.Count - 1) ? ", " : "");
        }

        return output;
    }
}

如果你只想要没有coulmn-headername的行的内容使用这个(空格分隔):

public static class Extender {
    public static string RowToString(this DataGridViewRow dgvr) {
        string output = "";

        foreach (DataGridViewCell cell in dgvr.Cells) {
            output += cell.Value.ToString() + " ";
        }

        return output.TrimEnd();
    }
}

您的代码将如下所示:

class YourClass
{
    private void saveButton_Click(object sender, EventArgs e)
    {
            saveFile1.DefaultExt = "*.txt";
            saveFile1.Filter = ".txt Files|*.txt|All Files (*.*)|*.*";
            saveFile1.RestoreDirectory = true;

            if (saveFile1.ShowDialog() == DialogResult.OK)
            {
                StreamWriter sw = new StreamWriter(saveFile1.FileName);

                List<string> theList = new List<string>();

                foreach (var line in theFinalDGV.Rows)
                {
                    string linecontent = line.RowToString();
                    if (linecontent.Contains("FUJI"))
                        richTextBox1.AppendText(linecontent + "\n");
                }
            }
    }
}

public static class Extender {
    public static string RowToString(this DataGridViewRow dgvr) {
        string output = "";

        DataGridView dgv = dgvr.DataGridView;

        foreach (DataGridViewCell cell in dgvr.Cells) {

            DataGridViewColumn col = cell.OwningColumn;
            output += col.HeaderText + ":" + cell.Value.ToString() + ((dgv.Columns.IndexOf(col) < dgv.Columns.Count - 1) ? ", " : "");
        }

        return output;
    }
}