2013-07-19 80 views
0

到目前爲止,我所有我使用列表視圖來檢索數據,並將其放在指定的文本框中,我想要的是,當我檢索或搜索數據時,它會自動將它們放在指定的文本框中,形式爲是否可以自動檢索數據庫中的數據?

private void btnretrieve_Click(object sender, EventArgs e) 
{ 
     con.Open(); 
     SqlCommand cmd = new SqlCommand("Select * from Information", con); 
     SqlDataAdapter dta = new SqlDataAdapter(cmd); 
     DataTable dt = new DataTable(); 

     dta.Fill(dt); 
     con.Close(); 
     lvwcontacts.Items.Clear(); 

     for (int index = 0; index < dt.Rows.Count; index++) 
     { 
      lvwcontacts.Items.Add(dt.Rows[index]["CONTACT_ID"].ToString()); 
      lvwcontacts.Items[index].SubItems.Add(dt.Rows[index]["CONTACT_NAME"].ToString()); 
      lvwcontacts.Items[index].SubItems.Add(dt.Rows[index]["CONTACT_ADDRESS"].ToString()); 
      lvwcontacts.Items[index].SubItems.Add(dt.Rows[index]["CONTACT_NO"].ToString()); 
} 
+0

另外:考慮爲你的連接,命令等實現'using'語句。 –

回答

0

隨着ListView你將無法做到這一點。然而,另一種方法可能是這樣的:

lvwcontacts.Items.AddRange(
    from r in dt.Select() 
    select new ListViewItem(r.ItemArray.Cast<string>().ToArray()) 
); 

但是,你還需要改變你的SELECT說法是:

Select CONTACT_ID, CONTACT_NAME, CONTACT_ADDRESS, CONTACT_NO from Information 
+0

我的意思是我想在不使用listview的情況下檢索數據 –

+0

@AirlynKheyTalara,你不用'ListView'來檢索數據。 –

+0

那是怎麼回事?我的代碼總是需要一個listview.im試圖不搜索沒有列表視圖 –

0

你可以把結果中的一類。首先,您需要創建一個聯繫人類。

Class Contact 
{ 
    '.. containing ID, Name, Address, No 
} 

然後我建議你把所有的邏輯放在一個函數中。在那裏,不是填充列表視圖,而是填充對象列表。

Public List<Contact> GetContacts() 
{ 
    List<Contact> contactList = new List<Contact>(); 

    con.Open(); 
     SqlCommand cmd = new SqlCommand("Select * from Information", con); 
     SqlDataAdapter dta = new SqlDataAdapter(cmd); 
     DataTable dt = new DataTable(); 

     dta.Fill(dt); 
     con.Close(); 


    for (int index = 0; index < dt.Rows.Count; index++) 
    { 
     Contact newContact = new Contact(); 

     newContact.ID = dt.Rows[index]["CONTACT_ID"]; 
     newContact.Name = dt.Rows[index]["CONTACT_NAME"]; 
     newContact.Address = dt.Rows[index]["CONTACT_ADDRESS"]; 
     newContact.NO = dt.Rows[index]["CONTACT_NO"]; 

     contactList.Add(newContact); 
    } 

    return contactList; 
} 

然後,您可以從列表中的任何地方你想要的數據。

*我還沒有編譯代碼。

+0

如果我沒有課程怎麼辦?他們有沒有必要創建一個班級? –

相關問題