2009-07-28 40 views
0

我有一個C#中的datagridview,當用戶單擊「搜索」時,它將根據搜索條件與客戶進行填充。我遇到的問題是,當用戶多次點擊搜索按鈕搜索客戶時,或者用戶想要執行其他搜索時,上次搜索中的所有詳細信息仍然位於datagridview中。現在的主要問題不是列沒有被刪除或額外添加,但datagridview中的按鈕的列索引在搜索多次後變爲「0」。清空DataGridView

現在我已經知道了這個問題,我想我會在這裏保留所有的細節,以防將來有人想查看細節。問題是,看來,當我刪除custDataGridView.DataSource = null;部分,一切似乎都工作

至於似乎有一些不確定性,這裏是代碼全:

 DataGridViewButtonColumn custAddJobSelect = new DataGridViewButtonColumn(); 
     Datatable dt = new Datatable(); 
     // ---> This was the culprit ---> custDataGridView.DataSource = null; 
     dt.Rows.Clear(); 

     #region SQL connection String 
     ...//CustQuery is the SQL stuff, conn is connection to DB. 
     #endregion 

     da = new System.Data.SqlClient.SqlDataAdapter(CustQuery, conn); 
     da.Fill(dt); 

     conn.Close(); 

     custDataGridView.DataSource = dt; 


     if (AddJobGone == false) 
     { 

      AddJobGone = true; 
      custAddJobSelect.DisplayIndex = 0; 
      custDataGridView.Columns.Add(custAddJobSelect); 
     } 

     private void custDataGridView_CellContentClick(object sender, DataGridViewCellEventArgs e) 
    { 
     if (e.ColumnIndex == this.custDataGridView.Columns.Count - 1) 
     { 
      string addJobsCustNo = custDataGridView.Rows[e.RowIndex].Cells[0].FormattedValue.ToString(); 
      txtAddJobsCustNo.Text = addJobsCustNo; 
      pnlAddJobSearchCustomer.Visible = false; 
     } 
    } 

感謝您的耐心,希望這可以幫助別人!

回答

0

現在的問題回答,似乎是一個問題:

custDataGridView.DataSource = null; 

看看全碼,如果你可以讓任何其他建議,請做:)

1

將數據源設置爲空應該做的竅門,確保您嘗試新的搜索時,您的特定代碼集正在被擊中。例如,將其插入到自己的過程中,並在搜索開始時調用該過程以確保該對象被清除。實際上,除非每次按下搜索按鈕時都沒有清除DataSource的原因,否則圍繞該代碼段的條件邏輯可能沒有意義。

0

什麼是您的數據源?它是DataTable,對象/實體列表,還是您手動將這些行添加到DataGridView?

這可能是顯而易見的,但如果您的數據源是DataTable或列表,則應確保在將新搜索結果添加到列表中之前將所有項從列表中刪除,而不是將注意力集中在DataGridView上本身。

我假設你目前DataSource = null解決方案不起作用,這將是一個顯而易見的解釋:)

0

我猜您要添加的行手動(dataGridView1.Rows.Add),其中如果將DataSource設置爲null,則不會執行任何操作。