将项目从一个GridView复制到另一个GridView

时间:2011-11-06 19:26:05

标签: c# asp.net gridview

我有一个Web用户控件,它有一个包含3列的表 1)GridView首先, 2)过滤选项(文本框)第二, 3)和另一个GridView在第三。

当我在filter(文本框)中输入文本时,会从数据库中选择一些行,并在第三列的GridView中显示。这个GridView有选择按钮,当它被按下时,我希望在第一列中将该行(或者只是它的一些列)添加到GridView。

据我所知,在这种情况下使用DataTable是很常见的。我的代码:

public partial class WebUserControl1 : System.Web.UI.UserControl
{
    DataTable tempTable = new DataTable();

    protected void Page_Load(object sender, EventArgs e)
    {
        tempTable.Columns.Add("ObjectID");
        tempTable.Columns.Add("Name");
        tempTable.Columns.Add("Price");
        currentDay.DataSource = tempTable;
    }

    protected void Button1_Click(object sender, EventArgs e)
    {
    }

    protected void objectChooser_SelectedIndexChanged(
        object sender, EventArgs e)
    { 
        DataRow newRow = tempTable.NewRow();
        newRow["ObjectID"] = objectChooser.SelectedRow.Cells[0].Text;
        newRow["Name"] = objectChooser.SelectedRow.Cells[1].Text;
        newRow["Price"] = objectChooser.SelectedRow.Cells[2].Text;           

        tempTable.Rows.Add(newRow);                        
        currentDay.DataBind();
    }

    protected void Button2_Click(object sender, EventArgs e)
    {
        DataClasses1DataContext dc = new DataClasses1DataContext();

        var objects = from p in dc.VisitingObjects
                  where p.City == tbCityFilter.Text
                  select p;

        objectChooser.DataSource = objects;
        objectChooser.DataBind();
    }
}

但这有点不对劲。当我第一次按下选择按钮(在GridView中)时,它可以工作(新值被添加到第一个GridView,但之后,按下选择按钮只会更改第一个GridView中的值,但不会添加新行。

你能否告诉我我的代码有什么问题,或者有更好的方法可以使用从GridView1到GridView2的复制值?

1 个答案:

答案 0 :(得分:1)

I feel like I've said this before ...

您需要将DataTable存储在回发之间不会消失的位置。会议可能是一个很好的起点。

objects = Session["data"]; //cast this
if (objects == null)
    //init objects to a new list of your obj type
objects = objects.Union (
    //your code for filtering grid rows
    );
Session["data"] = objects;