2012-06-19 43 views
1

我想暫時將一些數據從樹視圖中刪除到datagridview,但datagrid視圖已經從xml文件中加載了一些數據。無法將數據從樹形視圖複製到datagridview中的數據集

有人請向我解釋這個機制。

這是我的拖放功能://如果datagrid視圖中沒有數據,它就可以很好地工作。

private void DataGridView1OnDragDrop(object sender, DragEventArgs e) 
    { 
     Point dscreen = new Point(e.X, e.Y); 
     Point dclient = dataGridView1.PointToClient(dscreen); 
     DataGridView.HitTestInfo hitTest = dataGridView1.HitTest(dclient.X, dclient.Y); 

     if (hitTest.ColumnIndex == 0 && hitTest.Type == DataGridViewHitTestType.Cell) 
     { 
      e.Effect = DragDropEffects.Move; 
      //dataGridView1.Rows.Insert(hitTest.RowIndex, "hitTest", "hitTest", "hitTest", "hitTest"); 
      var data = (object[]) e.Data.GetData(typeof(string[])); 
      dataGridView1.Rows.Insert(hitTest.RowIndex, data); 

     } 
     else 
     { 
      e.Effect = DragDropEffects.None; 
     } 
     dataGridView1.AllowUserToAddRows = false; 
    } 

對於數據網格:

XmlReader xmlFile; 
xmlFile = XmlReader.Create("Product.xml", new XmlReaderSettings()); 
DataSet ds = new DataSet(); 
ds.ReadXml(xmlFile); 
dataGridView1.DataSource = ds.Tables[0]; 

對於樹形:

var filename = @"C:\Check.xml"; 
//First, we'll load the Xml document 
XmlDocument xDoc = new XmlDocument(); 
xDoc.Load(filename); 

回答

1

而不是增加拖放數據來控制你應該它添加到數據源的控制。在DebugMode

enter image description here

// will allow you to drop your data anywhere on gridview where a cell is 
if (hitTest.Type == DataGridViewHitTestType.Cell) 
{ 
    e.Effect = DragDropEffects.Move; 
    var data = (object[])e.Data.GetData(typeof(string[])); 

    // causes error - if there is already data bound to the control 
    // see image below 
    //dataGridView1.Rows.Insert(hitTest.RowIndex, data); 

    DataTable dt = (DataTable) dataGridView1.DataSource; 
    DataRow dr = dt.NewRow(); 
    dr.ItemArray = data; 
    dt.Rows.Add(dr); 
} 

錯誤消息對我來說工作得很好 - 如果有錯誤代碼顯示出來,讓我知道

+0

這是一個完美的解決方案。我還有兩個問題,1.我不能放在datagridview的任何地方。我怎樣才能把它放在datagridview的任何地方。 2.當我放棄時可以檢查重複值謝謝。 – linguini

+0

編輯答案,@你的第二個問題,你如何定義重複?哪些列有檢查? –

+1

你太棒了,太棒了。我想檢查第二個單元格,如果它已經存在於數據網格中然後顯示它。謝謝。 – linguini

相關問題