一个写入文件的异常
用 str = dataGridView1.CurrentRow.Cells[j].Value.ToString(); 获取dataGridView1中的数据写入没有问题,
但是 写入的只有dataGridView1表中的第一行数据
而用 //str = dataGridView1.Rows[i].Cells[j].Value.ToString(); 获取dataGridView1中的数据写入报异常;
未将对象引用设置到对象的实例.
下面是源码 看看如何解决:
DataTable dtGrid1 = null; //定义一个数据表
dtGrid1 = (DataTable)this.dataGridView1.DataSource; //获取datagridview里面的数据
SaveFileDialog sf = new SaveFileDialog(); //对话框
sf.Filter = @"txt文件(*.txt)|*.txt|所有文件(*.*)|*.*"; //定义保存的文件的类型
string str = "";
if (sf.ShowDialog() == DialogResult.OK) //如果确定保存
{
if (sf.FileName == "") //如果没有输入文件名
{
return;
}
try
{
StreamWriter sw = null; //文件流
sw = new StreamWriter(sf.FileName, false, Encoding.Unicode);
sw.WriteLine("dj订单编号\t\t单位名称\t\t时间\t\t时间\t\t状态\t\t备注"); //写入显示的标题
for (int i = 0; i < dataGridView1.RowCount; i++) //循环写入dataGridView中的内容
{
for (int j = 0; j < dataGridView1.ColumnCount; j++)
{
//str = dataGridView1.Rows[i].Cells[j].Value.ToString();
str = dataGridView1.CurrentRow.Cells[j].Value.ToString();
textBox1.Text = textBox1.Text + str + ",";
sw.Write(str + "\t\t");
}
sw.WriteLine("\n");
}
sw.Dispose(); //释放资源
sw.Close(); //关闭数据流
MessageBox.Show("数据导出成功!", "系统提示:");
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
MessageBox.Show("保存时发生未知错误,请稍后再试!", "系统提示:");
}
}
用 str = dataGridView1.CurrentRow.Cells[j].Value.ToString(); 获取dataGridView1中的数据写入没有问题,
但是 写入的只有dataGridView1表中的第一行数据
而用 //str = dataGridView1.Rows[i].Cells[j].Value.ToString(); 获取dataGridView1中的数据写入报异常;
未将对象引用设置到对象的实例.
下面是源码 看看如何解决:
DataTable dtGrid1 = null; //定义一个数据表
dtGrid1 = (DataTable)this.dataGridView1.DataSource; //获取datagridview里面的数据
SaveFileDialog sf = new SaveFileDialog(); //对话框
sf.Filter = @"txt文件(*.txt)|*.txt|所有文件(*.*)|*.*"; //定义保存的文件的类型
string str = "";
if (sf.ShowDialog() == DialogResult.OK) //如果确定保存
{
if (sf.FileName == "") //如果没有输入文件名
{
return;
}
try
{
StreamWriter sw = null; //文件流
sw = new StreamWriter(sf.FileName, false, Encoding.Unicode);
sw.WriteLine("dj订单编号\t\t单位名称\t\t时间\t\t时间\t\t状态\t\t备注"); //写入显示的标题
for (int i = 0; i < dataGridView1.RowCount; i++) //循环写入dataGridView中的内容
{
for (int j = 0; j < dataGridView1.ColumnCount; j++)
{
//str = dataGridView1.Rows[i].Cells[j].Value.ToString();
str = dataGridView1.CurrentRow.Cells[j].Value.ToString();
textBox1.Text = textBox1.Text + str + ",";
sw.Write(str + "\t\t");
}
sw.WriteLine("\n");
}
sw.Dispose(); //释放资源
sw.Close(); //关闭数据流
MessageBox.Show("数据导出成功!", "系统提示:");
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
MessageBox.Show("保存时发生未知错误,请稍后再试!", "系统提示:");
}
}
解决方案 »
免费领取超大流量手机卡,每月29元包185G流量+100分钟通话, 中国电信官方发货