0

我的应用程序有一个导出按钮,它打开一个保存文件对话框和一个下拉框,允许用户选择客户端和将文件保存到的路径,单击导出按钮后,我想从数据网格中获取数据客户端名称与下拉列表中的匹配并将其发送到文件,目前我的代码如下,但是它只返回列的标题,有人知道解决方案吗?:

      foreach (DataRow dr in this.CalcDataSet.MInve)
        {

            bool hasValue = false;

            for (int i = 0; i < dr.ItemArray.Count(); i++)
            {
                //if doesnt match selected client
                if    (!dr[i].ToString().Contains(dropboxClientList.SelectedValue.ToString()))
                hasValue = true;
            }

            //else 
            if (!hasValue) rowsToADD.Add(dr);

            foreach (DataRow field in rowsToADD)
            {   
              str.Append(field.ToString() + ",");
            }
            str.Replace(",", "\n", str.Length - 1, 1);
        }


        try
        {
            System.IO.File.WriteAllText(Filepath, str.ToString());
        }
        catch (Exception ex)
        {
            MessageBox.Show("Write Error :" + ex.Message);
        }
4

1 回答 1

0

取自这篇 SO 帖子

string file_name = "C:\\test1.txt";

System.IO.StreamWriter objWriter;

objWriter = new System.IO.StreamWriter(file_name);

int count = dgv.Rows.Count;

for (int row = 0; row < count; row++)
{
    int colCount = dgv.Rows[row].Cells.Count;

    // EDIT inserted if statement
    string selectedValue = dropboxClientList.SelectedValue.ToString();
    string clientName = dgv.Rows[row].Cells[1].Value.ToString();

    // If the current row contains the selected client name 
    if (clientName.Contains(selectedValue)
    {
        // Write the columns for the current row
        for ( int col = 0; col < colCount; col++)  
        {            
            objWriter.WriteLine(dgv.Rows[row].Cells[col].Value.ToString());
        }
    }

    // record seperator could be written here.
}

objWriter.Close();
于 2013-08-13T10:21:07.897 回答