2016-04-03 123 views
0

檢索的列表框項目我沒有什麼問題我試圖在前面添加序列號數據,我將從SQL Server數據庫中檢索數據,如下所示。添加序列號到SqlDataReader()

public partial class Form1 : Form 
{ 
    SqlConnection con = new SqlConnection(@"Server=.;database=test;integrated security=false;user id=sa;[email protected]"); 
    SqlCommand com = new SqlCommand(); 

    SqlDataReader dr; 

    public Form1() 
    { 
     InitializeComponent(); 
     com.CommandText = "select book_name from Table_book"; 
     com.Connection = con; 
     con.Open(); 

     dr = com.ExecuteReader(); 

     while (dr.Read()) 
     { 
      for (int i = 1; i <= dr.FieldCount; i++) 
      { 
       listBox1.Items.Add(i+"-"+dr[0].ToString()); 
       i += i; 
      } 
     } 

     if (listBox1.Items.Count == 0) 
     { 
      MessageBox.Show("No Data Found");    
     } 

     dr.Close(); 
     con.Close(); 
    } 

而結果會是這樣的:

enter image description here

TY所有

+1

爲什麼不使用服務器端的序列號?它應該簡化您的代碼並使結果更加一致。看看這個:[ROW_NUMBER(Transact-SQL)](https://msdn.microsoft.com/en-CA/library/ms186734.aspx)。它是一個分區函數,但是您可以省略分區並只指定ORDER BY,請參閱示例。 – Neolisk

回答

0

我只是用我的服務器ID序列來解決這樣的問題:

SqlConnection con = new SqlConnection(@"server=.;database=test;integrated security=false;user id=sa;[email protected]"); 
     con.Open(); 
     SqlCommand sqlcom = new SqlCommand("select book_id,book_name from Table_book", con); 
     SqlDataReader sqlDR=sqlcom.ExecuteReader(); 
     while(sqlDR.Read()) 
     { 
     listBox1.Items.Add(sqlDR["book_id"].ToString()+"-"+sqlDR["book_name"].ToString()); 
     } 
-1

你的 「序列號」 設置爲領域在返回的數在使用dr.Read()迭代遍歷每行時,結果是一致的。 for循環沒有必要。你應該做的是設置你的計數器變量dr.Read()外面,然後裏面遞增它...

int i = 1; 
while (dr.Read()) 
{ 
    // set listbox item text 
    listBox1.Items.Add(i.ToString() + "-" + dr[0].ToString()); 
    i+=1; 
} 
+0

這給了我錯誤索引超出範圍異常未處理 –

+0

不知道如何從它得到一個'IndexOutOfRange'異常... – ffa

+0

它給我的錯誤還因爲只有一次是我們第一次進入while循環所有字段計數的所有數據。所以我們需要在while循環中使用for循環... – nick

0

Add能夠在對象操作的,不只是字符串。 爲什麼?

class ModelClass { 

    // for use in algorithm, may be presented in GUI or not 
    int Sequence { get; set; } 

    string Description { get ; set ;} 
    // ... what You want, is is typical model class 

    override string ToString() { 
    // return what you want, is presented in GUI 
    return Descrition; 
    } 
    ModelClass(string n, int i) ... 
} 
... 

    listBox.Items.Add(new ModelClass(i.ToString(), dr[...] // sequence) 

現在你可以從Items中檢查任何你想要的東西,因爲這些都是ModelClass的對象。

手動編寫代碼,未在IDE中測試過。