我有一个奇怪的问题。我有TabControl
两个TabPages
。每个页面都有一个datagridview
. 两者datagridviews
都填充了XML
文件。
我希望两者都AutoSizeColumnsMode
设置为“ Fill
” DataGridViews
。我想在我的代码中设置列的宽度。
一切正常,TabPage1
但设置宽度DataGridView
onTabPage2
抛出NullReferenceException
.
我真的不明白,因为我做与 for 相同的事情datagridview1
并且工作正常但datagridview2
抛出异常。此外,如果我选择任何AutoSizeColumnsMode
值,但Fill
.
这是代码:
XmlReader xmlFile = XmlReader.Create("File1.xml", new XmlReaderSettings());
DataSet ds = new DataSet();
ds.ReadXml(xmlFile);
dataGridView1.DataSource = ds.Tables[0];
dataGridView1.Sort(dataGridView1.Columns[1], ListSortDirection.Ascending);
dataGridView1.Columns[0].Width = 35;
dataGridView1.Columns[1].Width = 248;
dataGridView1.Columns[2].Width = 110;
dataGridView1.Columns[3].Width = 140;
dataGridView1.Columns[9].Width = 127;
dataGridView1.Columns[0].Visible = false;
dataGridView1.Columns[1].Visible = true;
dataGridView1.Columns[2].Visible = true;
dataGridView1.Columns[3].Visible = true;
dataGridView1.Columns[4].Visible = false;
dataGridView1.Columns[5].Visible = false;
dataGridView1.Columns[6].Visible = false;
dataGridView1.Columns[7].Visible = false;
dataGridView1.Columns[8].Visible = false;
dataGridView1.Columns[9].Visible = true;
dataGridView1.Columns[10].Visible = true;
dataGridView1.Columns[10].Width = 100;
xmlFile.Close();
XmlReader xmlFile2= XmlReader.Create("File2.xml", new XmlReaderSettings());
DataSet ds2 = new DataSet();
ds2.ReadXml(xmlFile2);
dataGridView2.DataSource = ds2.Tables[0];
dataGridView2.Columns[0].Width = 135; // The exception is thrown here
dataGridView2.Columns[9].Width = 200;
dataGridView2.Columns[8].Width = 300;
dataGridView2.Columns[7].Width = 70;
dataGridView2.Columns[6].Width = 70;
dataGridView2.Columns[5].Width = 124;
dataGridView2.Columns[4].Width = 81;
dataGridView2.Columns[3].Width = 70;
dataGridView2.Columns[2].Width = 70;
dataGridView2.Columns[1].Width = 124;
dataGridView2.Columns[0].Visible = true;
dataGridView2.Columns[1].Visible = true;
dataGridView2.Columns[2].Visible = true;
dataGridView2.Columns[3].Visible = true;
dataGridView2.Columns[4].Visible = true;
dataGridView2.Columns[5].Visible = false;
dataGridView2.Columns[6].Visible = false;
dataGridView2.Columns[7].Visible = false;
dataGridView2.Columns[9].Visible = false;
xmlFile2.Close();