[英]Pass data from one form to a specific cell in a datagridview from another form in C#
[英]pass datagridview from one form to another c#
我想將我的datagridview從form1傳遞到form2。我嘗試使用構造函數,但沒有結果,第二種形式的datagridview為空。 有人可以在這里幫助我,我被堆積了幾個小時。我不使用sql,也不需要使用dataTable.Here是我的代碼:
我將datagridview3填充到datagridview2的cellClick事件上。 當我單擊dayagridview2 cellClick_event時,我的datagridview3填充了以下方法:
private void dataGridView2_CellClick(object sender, DataGridViewCellEventArgs e)
{
DataD d = new DataD();
d.Mat(dataGridView1,dataGridView2,dataGridView3);
}
這是填充dataGridView3的方法:
public void Mat(DataGridView dataGridView1, DataGridView dataGridView2,DataGridView dataGridView3)
{
Named n = new Named();
foreach (DataGridViewCell cell in dataGridView2.SelectedCells)
{
IList<String> lista = new List<String>();
n.Data = string.Empty;
n.Data2 = string.Empty;
int indexOfYourColumn = 9;
int index2 = 0;
var restaurantList = new List<Named>();
foreach (DataGridViewRow row in dataGridView1.Rows)
{
n.Data = row.Cells[indexOfYourColumn].Value.ToString();
if (cell.Value.ToString() == n.Data.ToString())
{
restaurantList.Add(new Nalozi()
{
Data = row.Cells[indexOfYourColumn].Value.ToString(),
Data2 = row.Cells[index2].Value.ToString()
});
}
}
dataGridView3.DataSource = restaurantList;
}
}
所以現在我只需要在buttnClick上以另一種形式顯示此dataGridView3。
如果要將DataGridView
從一種形式傳遞到另一種形式,則可能必須將DataGridView.DataSource
的DataGridView
從一種形式傳遞給另一種形式。 像這樣
new SecondForm(dataGridView.DataSource)
然后您的SecondForm
將接受傳遞的DataSource
並將其傳遞給該表單的DataGridView
class SecondForm
{
public SecondForm(object dataSource)
{
InitializeComponents();
dataGridView.DataSource = dataSource;
}
}
如果要傳遞DataSource
副本,則可以根據FirstForm
DataGridView
內部的現有數據創建一個新的DataTable
private DataTable GetDataTableFromDGV(DataGridView dgv)
{
var dt = new DataTable();
foreach (DataGridViewColumn column in dgv.Columns)
{
if (column.Visible)
{
// You could potentially name the column based on the DGV column name (beware of dupes)
// or assign a type based on the data type of the data bound to this DGV column.
dt.Columns.Add();
}
}
object[] cellValues = new object[dgv.Columns.Count];
foreach (DataGridViewRow row in dgv.Rows)
{
for (int i = 0; i < row.Cells.Count; i++)
{
cellValues[i] = row.Cells[i].Value;
}
dt.Rows.Add(cellValues);
}
return dt;
}
並更新對此的首次呼叫
new SecondForm(GetDataTableFromDGV(dataGridView))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.