2011-02-05 27 views

Trả lời

21

Tự tạo các cột cho DataGridView. Hãy thử một cái gì đó như thế này.

DataGridView dataGridView1 = new DataGridView(); 
BindingSource bindingSource1 = new BindingSource(); 

dataGridView1.ColumnCount = 2; 

dataGridView1.Columns[0].Name = "Field1"; 
dataGridView1.Columns[0].DataPropertyName = "Field1"; 
dataGridView1.Columns[1].Name = "Field2"; 
dataGridView1.Columns[1].DataPropertyName = "Field2"; 

bindingSource1.DataSource = GetDataTable(); 
dataGridView1.DataSource = bindingSource1; 
0

Chúng tôi có thể tạo một DataTable mới với các cột bắt buộc và thêm hàng vào nó từ Tập dữ liệu. Sau đó, chúng ta có thể khởi tạo DataGrid với DataTable mới được tạo ra.

dt = new DataTable();   
dt_Property.Columns.Add("Field1"); 
dt_Property.Columns.Add("Field2"); 
int i = 0; 
DataRow row = null; 
foreach (DataRow r in ds.Tables[0].Rows) 
{    
    row = dt.NewRow();      
    row["Field1"] = ds.Tables[0].Rows[i][1]; 
    row["Field2"] = ds.Tables[0].Rows[i][2]; 
    dt_Property.Rows.Add(row); 
    i = i + 1; 
} 

dataGridView1.DataSource = dt; 
16

Thêm cột như trên câu trả lời, và không quên đặt:

dataGridView1.AutoGenerateColumns=false; 
+1

Lời nhắc tuyệt vời. Cảm ơn. Đã lưu ngày của tôi. – user1298925

1

này được hỏi một thời gian trước đây, vì vậy bạn có thể sẽ không cần câu trả lời này ... Hy vọng rằng những người khác sẽ tìm thấy nó hữu ích.

Tôi phải làm điều gì đó tương tự và tôi thấy rằng giải pháp đơn giản nhất là tạo bản sao tạm thời của bảng (trong đó dữ liệu của bạn được lưu trữ) và sau đó chỉ cần xóa cột được đề cập. Ví dụ:

DataTable temp = YourDataTable; 
temp.Columns.Remove(temp.Columns[2]) // Will remove the third column for example 
YourDataTable.DataSource = temp; 
YourDataTable.DataBind(); 

Tôi nghĩ điều này nên thực hiện thủ thuật!

Chúc mừng!

0
private void Form1_Load(object sender, EventArgs e) 
    { 
     SqlConnection con = new SqlConnection("connection string"); 
     SqlDataAdapter adp = new SqlDataAdapter("select Fieldname1,fieldname2 from Table Name", con); 
     DataSet ds = new DataSet(); 
     ds.Clear(); 
     adp.Fill(ds); 
     if (ds.Tables[0].Rows.Count > 0) 
     { 
      dataGridView1.DataSource = ds.Tables[0]; 
    } 

Chắc chắn nó sẽ hoạt động.

0

Liên kết DataTable với DataGridView sau đó ẩn cột bạn không muốn.

dataGridView1.DataSource = datatable; 
dataGridView1.Columns["ColumnName"].Visible = false; 
Các vấn đề liên quan