Click here to Skip to main content
15,896,493 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hello Friends,
I am new in C#.net few day back i try a assignment of datagrid & also search a lot solution of that but not get any fine solution yet. My assignment is we have 2 datagrid source & target . i have to firstly transfer selected rows from source to target(source fetch data like from the table Student) then the target datagrid rows which i have copied save into other table(like top student).

So please help me for that
Posted

Hi,

What you need to do is the following:
Set the data source for the source datagrid. On the selected index change, get the selected row and copy it to the data source of the target datagrid. In my scenario, the source datagrid has the first column as a template column containing the select button/text.

C#
protected void gvSource_SelectedIndexChanged(object sender, EventArgs e)
{
    //get selected row
    object[] obj = new object[2];
    obj[0] = gvSource.Rows[gvSource.SelectedIndex].Cells[1].Text;
    obj[1] = gvSource.Rows[gvSource.SelectedIndex].Cells[2].Text;
    
    //get existing data in target datagrid
    DataTable dtTarget = (DataTable)gvTarget.DataSource;
    
    //add selected row
    dtTarget.Rows.Add(obj);

    gvTarget.DataSource = dtTarget;
    gvTarget.DataBind();
}
 
Share this answer
 
Assuming that you have a button which should transfer selected items to another datagrid, you can use the following:
data source:
private DataTable _students;
private DataTable _topStudents;

private void Form1_Load(object sender, EventArgs e)
{
// init data tablres
    _students = new DataTable("Students");
    _topStudents = new DataTable("TopStudents");
    _topStudents.Columns.Add("name", typeof (string));
    _students.Columns.Add("name", typeof(string));
// put in some data
    _students.LoadDataRow(new object[] {"john"}, true);
    _students.LoadDataRow(new object[] {"paul"}, true);
    _students.LoadDataRow(new object[] {"jack"}, true);
// setup data sources
    dataGridViewSource.DataSource = _students;
    dataGridViewTarget.DataSource = _topStudents;
}

copying selected rows:
C#
private void buttonTransfer_Click(object sender, EventArgs e)
{
// iterate through selected rows
    foreach (var row in dataGridViewSource.SelectedRows)
    {
        var dataRow = row as DataGridViewRow;
        if (dataRow != null)
        {
// get an array of values and load a row to the target table.
            var values = ((DataRowView)dataRow.DataBoundItem).Row.ItemArray;
            _topStudents.LoadDataRow(values, true);
        }
    }
}
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900