我有1個表單,其中button1 draw table at datagridview。 填充單元格後,我需要將數據從datagridview保存到xml通過button2。將datagridview保存到xml中
//save
private void button1_Click(object sender, EventArgs e)
{
try
{
DataSet ds = new DataSet();
ds = (DataSet)(dataGridView1.DataSource);
ds.WriteXml(@"c:\1.xml");
}
catch (Exception ex)
{
MessageBox.Show("Ошибка: " + ex.Message);
}
}
//draw a datagridview
private void button2_Click(object sender, EventArgs e)
{
try
{
int x, y;
x = Convert.ToInt32(textBox1.Text);
y = Convert.ToInt32(textBox2.Text);
double[,] grid;
grid = new double[x, y];
int k = 0;
k = dataGridView1.ColumnCount;
if (k != 0)
for (int i = 0; i < k; i++)
dataGridView1.Columns.RemoveAt(0);
dataGridView1.Columns.Clear();
AddColumns(y, dataGridView1);
AddRows(x, dataGridView1);
dataGridView1.RowHeadersWidth = 22;
}
catch (Exception ex)
{
MessageBox.Show("Ошибка: " + ex.Message);
}
}
,但我收到的錯誤:
object reference not set to an instantce of an object.
所以,我怎麼能保存的datagridview到XML?
你能告訴我們你把數據源設置到datagridview的代碼嗎? – 2012-03-01 11:13:29
顯然沒有綁定到datagridview控件的DataSource。你如何使用這個數據網格?有更多的代碼會很好.. – 2012-03-01 11:13:45