如何在编辑模式下保留gridview选择命令?

时间:2013-06-18 15:20:05

标签: c# asp.net gridview webforms

我有一个gridview,允许用户根据StandardView(基本select * from table)和CurrentView之间的单选按钮列表值更改gridview select命令(此查询显示今天所有项目的列表),我在表单加载之前公开声明了两个字符串。当用户单击“编辑”时,gridview会执行回发,并将其发送回标准视图。

这是我的数据表:

private DataTable GetData(SqlCommand cmd)
{
    DataTable dt = new DataTable();
    SqlConnection con = new SqlConnection(conn);
    SqlDataAdapter sda = new SqlDataAdapter();
    cmd.CommandType = CommandType.Text;
    cmd.Connection = con;
    con.Open();
    sda.SelectCommand = cmd;
    sda.Fill(dt);
    return dt;
    con.Close();
}

这是我的onrowediting

protected void EditItem(object sender, GridViewEditEventArgs e)
{
    SqlConnection con = new SqlConnection(conn);
        SqlCommand cmd = new SqlCommand();
        cmd.CommandType = CommandType.Text;
        string EditView = StandardView;
        switch (rblChooseEditView.SelectedValue)
        {
            case "1":
                EditView = StandardView;
                cmd.CommandText = EditView;
                gvMainView.EditIndex = e.NewEditIndex;
                BindData();
                break;

            case "2":
                EditView = CurrentView;
                cmd.CommandText = EditView;
                gvMainView.EditIndex = e.NewEditIndex;
                BindData();
                break;
        }
}

EDITED

我想要包含我的表单,BindData()和一个名为RetainEditSelect()的新方法,以便添加您给我的建议。我仍然没有取得任何成功。

protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
           BindData();
           RetainEditSelect(); 
        }

    }

    private void BindData()
    {
        //String for Main GridView
        string strMainQuery = StandardView;
        SqlCommand cmdMain = new SqlCommand(strMainQuery);
        switch (rblChooseEditView.SelectedValue)
        {
            case "1":
                strMainQuery = StandardView;
                gvMainView.DataSource = GetData(cmdMain);
                gvMainView.DataBind();
                break;

            case "2":
                strMainQuery = CurrentView;
                gvMainView.DataSource = GetData(cmdMain);
                gvMainView.DataBind();
                break;
        }
    }  

这是我的新方法

    private void RetainEditSelect()
    {
        using (SqlConnection con = new SqlConnection(conn))
        {
            SqlCommand cmd = new SqlCommand();
            cmd.CommandType = CommandType.Text;
            string EditView = StandardView;
            switch (rblChooseEditView.SelectedValue)
            {
                case "1":
                    EditView = StandardView;
                    cmd.CommandText = EditView;
                    BindData();
                    break;

                case "2":
                    EditView = CurrentView;
                    cmd.CommandText = EditView;
                    BindData();
                    break;
            }
        }         

    }

0 个答案:

没有答案