2014-09-20 56 views
0

我在我的winform應用程序上有Textbox1,dataGridView和一個按鈕。 情景是:按下按鈕時,SQL Query將根據在文本框中輸入的值運行。並將這個查詢獲取的數據插入到dataGridview(dataTable)中。直到這裏,我的代碼正在工作。 但是當我在文本框中鍵入其他值並按下按鈕時,它將替換dataGridview(dataTable)中存在的記錄。 我希望每次當我在文本框中鍵入一些值並按下按鈕時,應該在dataGridview(dataTable)中添加row()。它不應該取代之前添加的數據。 以下是我的代碼:我需要滿足以下要求:新增加的數據不應取代之前的數據。 在此先感謝。 使用sql查詢在運行時在數據表中添加行

private void button1_Click(object sender, EventArgs e) 
    { 
     try 
     { 

      SqlConnection con = new SqlConnection(@"Data Source=AFZAL\SQLEXPRESS;Initial Catalog=GIMS_LabInfo;Integrated Security=True"); 
      con.Open(); 
      SqlCommand sc = new SqlCommand("select Profcode, Profname, Profcharges, Profduedate from Profnames$ Where Profname = '"+comboBox1.Text+"'", con); 
      SqlDataAdapter sda = new SqlDataAdapter(sc); 

      DataTable ds = new DataTable(); 

       sda.Fill(ds); 
      dataGridView2.DataSource = ds; 

     } 
     catch (Exception ex) 
     { 
      MessageBox.Show(ex.Message); 
     } 
    } 

回答

0

您應該有一個全局變量,它包含通過各種查詢加載到網格中的行,並且它用於將其內容綁定到DataGridView。

DataTable currentData = null; 

然後,在第一次查詢後,您可以使用DataTable.Copy方法複製表,由查詢返回的數據並綁定該currentData到DataGrid。
接下來的查詢使用LoadDataRow方法

private void button1_Click(object sender, EventArgs e) 
{ 
    try 
    { 
     using(SqlConnection con = new SqlConnection(....)) 
     using(SqlCommand sc = new SqlCommand(@"select Profcode, Profname, Profcharges, 
            Profduedate from Profnames$ 
            Where Profname = @name", con)) 
     { 
      con.Open(); 
      cmd.Parameters.AddWithValue("@name",comboBox1.Text); 
      SqlDataAdapter sda = new SqlDataAdapter(sc); 

      DataTable ds = new DataTable(); 
      sda.Fill(ds); 

      if(currentData == null) 
      { 
       currentData = ds.Copy(); 
       dataGridView2.DataSource = currentData; 
      } 
      else 
      { 
       currentData.BeginLoadData(); 
       foreach(DataRow row in ds.Rows) 
        currentData.LoadDataRow(row.ItemArray, true); 
       currentData.EndLoadData(); 

      } 
     } 
    } 
    catch (Exception ex) 
    { 
     MessageBox.Show(ex.Message); 
    } 
}  

還要注意,我在建設命令文本中刪除字符串連接和使用,而不是一個參數化查詢添加提取到currentData表中的行。使用語句也確保正確關閉和處理使用的命令和連接。

+0

非常感謝你@steve。但我在這一行上得到錯誤currentData.LoadDataRow(row.ItemArray);錯誤:方法'LoadDataRow'沒有重載需要'1'參數 – 2014-09-20 15:38:29

+0

沒錯,我沒有正確檢查文檔。還有一個參數可以保持行在Unchanged狀態下添加。回答更新 – Steve 2014-09-20 16:59:14

+0

謝謝sooooooo史蒂夫。過去4天我一直在這樣做,但不能成功。你做到了人!再次感謝你:) – 2014-09-20 17:31:36

0

在您的代碼中,您沒有任何命令將TextBox中的值添加到DataGridView。添加值的代碼應該是這樣的:

dataGridView1.Rows [0] .Cells [0] .Value = textBox1.Text;

0

我想你想清除你的datagridview之前插入數據源在網格視圖。 等你按鈕首先點擊此處

dataGridView1.DataSource = null;