[英]Error When Looping Through DataSet and Inserting into ListBox
這是Windows窗體應用程序。 我有一個類Program.cs和一個帶有ListBox的表單DeployerConsole.cs。 我試圖遍歷SQL查詢的結果。 我遇到麻煩,並且收到“對象引用未設置為對象實例”的信息。 當我嘗試訪問數據並將其插入到表單上的列表框中時發生錯誤。
編輯:SQL查詢成功完成,並且Console.WriteLine使用正確的數據正確輸出到輸出窗口。
static void LoadServers()
{
DeployerConsole DC = (DeployerConsole)Application.OpenForms["DeployerConsole"];
//DeployerConsole DC = new DeployerConsole();
SqlConnection myConnection = new SqlConnection("server=XXX; database=XXX; uid=XXX; pwd=XXX;Integrated Security=true;Connection Lifetime=5;Trusted_Connection=yes;");
myConnection.Open();
DataSet ds = new DataSet();
SqlCommand myCommand = new SqlCommand("SELECT ServerName FROM DeployServers", myConnection);
SqlDataAdapter adapter = new SqlDataAdapter(myCommand);
adapter.Fill(ds);
DataTable dt = ds.Tables[0];
foreach (DataRow dr in dt.Rows)
{
DC.listBox1.Items.Add(dr["ServerName"].ToString());
Console.WriteLine(dr["ServerName"].ToString());
}
}
編輯:添加了屏幕截圖
有人對我做錯了什么建議或指導嗎?
編輯(答案):嗯,我將代碼從類移到了表單。 現在訪問listBox沒問題。 但是,我仍然想知道解決方案。
嘗試一下(僅出於測試目的)可能值得嘗試:
if(DC.listBox1 != null)
{
DC.listBox1.Items.Add(dr["ServerName"].ToString());
}
如果您可能需要確保某個地方的listBox1被實例化,那可能會給您一個線索。
DC.listBox1 = new ListBox();
編輯
可能是由於未通過引用靜態方法正確傳遞DC。 最好更改方法的簽名以接受表格。
static void LoadServers(Form form)
{
...
form.listBox1.Items.Add(...)
... etc.
}
並通過以下形式進行調用:
Helper.LoadServers(this);
您的問題可能是由以下代碼行引起的:
DeployerConsole DC = (DeployerConsole)Application.OpenForms["DeployerConsole"];
我懷疑OpenForms屬性返回null,因為您尚未顯式設置表單名稱(例如form.Name =“ DeployerConsole”;)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.