2016-12-02 62 views
-2
using System; 
using System.Collections.Generic; 
using System.ComponentModel; 
using System.Data; 
using System.Drawing; 
using System.Linq; 
using System.Text; 
using System.Threading.Tasks; 
using System.Windows.Forms; 
using System.Data.SqlClient; 


namespace ArsCRM 
{ 
public partial class Form1 : Form 
{ 

    public Form1() 
    { 
     InitializeComponent(); 
    } 

    private void Form1_Load(object sender, EventArgs e) 
    { 
     SqlConnection con = new SqlConnection(); 
     con.ConnectionString = @"Data Source=test\s08r2;Initial Catalog=Demo;User id=sa;Password=123456"; 
     con.Open(); 
     SqlDataAdapter sda = new SqlDataAdapter(@" 
      SELECT acSubject, acAddress, acPost, acName, acPhone, 
      acFieldSA, acFieldSB, acFieldSC, acFieldSD, acFieldSE, 
      anFieldNA, anFieldNB, anFieldNC, anFieldND, anFieldNE, OdgovornaOsoba, acSubjTypeBuyer 
      FROM ARS.dbo._ARSCRM_vSubjekti order by acSubject 
      ", con); 
     DataTable dt = new DataTable(); 
     sda.Fill(dt); 
     dataGridView1.DataSource = dt; 


     } 


    private void txtSearch_TextChanged(object sender, EventArgs e) 
    { 
     if (string.IsNullOrEmpty(txtSearch.Text)) 
     { 
      (dataGridView1.DataSource as DataTable).DefaultView.RowFilter = string.Empty; 
     } 
     else 
     { 
      (dataGridView1.DataSource as DataTable).DefaultView.RowFilter = string.Format("acSubject like '%{0}%'", txtSearch.Text); 
     } 
    } 

    private void dataGridView1_SelectionChanged(object sender, EventArgs e) 
    { 


     DataGridView dgv = (DataGridView)sender; 

     if (dgv.SelectedCells.Count > 0) 
      txtAcFieldSA.Text = dgv.Rows[dgv.SelectedCells[0].RowIndex].Cells[5].Value.ToString();    
    } 

} 
} 

我有這個代碼,它在最後兩行填滿txtAcFieldSA與選定的行6.列。C#從dataGridView1填充ComboBox1

我想在ComboBox1一些事情。當我選擇ComboBox1填充6.列中的某一行時。那可能嗎?

+0

的問題是不理解,你可以請重寫的問題嗎? – iceDragon

+0

請重新編寫問題,因爲它沒有意義 –

+0

羅馬諾已經解決了這個問題。我需要ComboBox1填充來自dataGridView1中選定行的6列。 – kole1108

回答

1

過不去做根據文本框

private void dataGridView1_SelectionChanged(object sender, EventArgs e) 
      { 


       DataGridView dgv = (DataGridView)sender; 

       if (dgv.SelectedCells.Count > 0) 
       { 
        txtAcFieldSA.Text = dgv.Rows[dgv.SelectedCells[0].RowIndex].Cells[5].Value.ToString(); 
        ComboBox1.Text = dgv.Rows[dgv.SelectedCells[0].RowIndex].Cells[6].Value.ToString(); 
       } 
      } 

,或者如果你想將其作爲項目添加到ComboBox:

private void dataGridView1_SelectionChanged(object sender, EventArgs e) 
     { 


      DataGridView dgv = (DataGridView)sender; 

      if (dgv.SelectedCells.Count > 0) 
      { 
       txtAcFieldSA.Text = dgv.Rows[dgv.SelectedCells[0].RowIndex].Cells[5].Value.ToString(); 

       ComboBox1.Items.Add(dgv.Rows[dgv.SelectedCells[0].RowIndex].Cells[6].Value.ToString();) 
      } 
     } 
+0

如果沒有選定的單元格,此代碼會發生什麼?也請重新格式化,以便人們可以實際閱讀它 – TheLethalCoder

+0

這與上一個功能的問題代碼的1:1副本有何不同? – grek40

+0

你說得對。我忘了括號。但你爲什麼給我命令。你可以自己重新格式化代碼。謝謝! –