这是我的代码
connection.Open();
try
{
adpSup.SelectCommand = new SqlCommand("SELECT Supplier_Supplier AS 'Supplier', Supplier_TP AS 'Telephone', Supplier_EMail AS 'E-Mail', Supplier_Address AS 'Address' FROM Supplier", connection);
dsSup.Clear();
adpSup.Fill(dsSup, "tblSupplier");
dgSupplier.DataSource = dsSup.Tables["tblSupplier"];
dgSupplier.Columns["Telephone"].Width = 70;
foreach (DataGridViewColumn col in dgSupplier.Columns)
{
col.HeaderCell.Style.Alignment = DataGridViewContentAlignment.MiddleCenter;
col.HeaderCell.Style.Font = new Font("Arial", 12F, FontStyle.Bold, GraphicsUnit.Pixel);
}
}
catch (SqlException ex)
{
MessageBox.Show(ex.Message, "Report", MessageBoxButtons.AbortRetryIgnore, MessageBoxIcon.Error);
}
finally
{
connection.Close();
}
当我运行此代码时,它显示“System.Windows.Forms.dll中发生类型'System.NullReferenceException'的未处理异常。附加信息:对象引用未设置为对象的实例。” 我不知道错误是什么,请帮帮我
答案 0 :(得分:0)
将您的Catch语句替换为:
catch (Exception ex)
{
MessageBox.Show(ex.ToString(), "Report", MessageBoxButtons.AbortRetryIgnore, MessageBoxIcon.Error);
}
这样您就可以看到发生错误的行号
答案 1 :(得分:-1)
你解决了这个问题吗? 我使用DataGridView时也遇到了这个问题。 最后,我通过“委托”解决了这个问题。
所以我想,你的代码中的块
dgSupplier.DataSource = dsSup.Tables["tblSupplier"];
dgSupplier.Columns["Telephone"].Width = 70;
foreach (DataGridViewColumn col in dgSupplier.Columns)
{
col.HeaderCell.Style.Alignment = DataGridViewContentAlignment.MiddleCenter;
col.HeaderCell.Style.Font = new Font("Arial", 12F, FontStyle.Bold, GraphicsUnit.Pixel);
}
应该由代表运行。
这就是我在代码中弄清楚的方法:
//prepare data in other thread:
String line;
String[] split = null;
DataTable table = new DataTable();
DataRow row = null;
StreamReader sr = new StreamReader(pCsvPath, Encoding.Default);
line = sr.ReadLine();
split = line.Split(',');
foreach (String colname in split)
{
table.Columns.Add(colname, System.Type.GetType("System.String"));
}
//fill the data to the datatable
int j = 0;
while ((line = sr.ReadLine()) != null)
{
j = 0;
row = table.NewRow();
split = line.Split(',');
foreach (String colname in split)
{
row[j] = colname;
j++;
}
table.Rows.Add(row);
}
sr.Close();
//use the delegate
parent.showDataview(table.DefaultView);
follow是主线程中的委托代码
private delegate void ShowDatagridView(DataView dataView);
public void showDataview(DataView dataView)
{
if (this.InvokeRequired)
{
ShowDatagridView show = new ShowDatagridView(showDataview);
this.Invoke(show, new object[] { dataView });
}
else
{
pmGridview.DataSource = dataView;
}
}
希望对你有所帮助!