ASP.Net Gridview,如何激活基于ID的编辑模式(DataKey)

时间:2009-01-13 06:23:24

标签: asp.net gridview

我有一个页面,我们称之为SourceTypes.aspx,它有一个显示源类型列表的GridView。 GridView的一部分是DataKey,SourceTypeID。如果源TypeID通过查询sting传递给页面,如何根据SourceTypeID将Gridview置于编辑模式适当的行?

GridView绑定到SQlDataSource对象。

我有一种感觉,当答案出现时我会踢自己!!

我看过Putting a gridview row in edit mode programmatically,但这是一些缺乏细节

2 个答案:

答案 0 :(得分:2)

当你想根据数据将其置于编辑模式时,这有点棘手。您告诉datagrid哪些显示的行是可编辑的,而不是您想要编辑的数据,因此您需要遍历网格中的每一行,看它是否与id匹配,并将EditItemIndex设置为适当的价值和重新绑定。

您可以查看源数据并在绑定之前从中获取行号,但是您可能遇到分页,排序等问题。

重新绑定网格有点麻烦,但我想不出更好的方法。

public partial class _Default : System.Web.UI.Page
{

    private DataTable GetData()
    {
        DataTable tTable = new DataTable();
        tTable.Columns.Add(new DataColumn("Column1", typeof(int)));
        tTable.Columns.Add(new DataColumn("Column2", typeof(string)));

        DataRow tRow = tTable.NewRow();
        tRow["Column1"] = 1;
        tRow["Column2"] = "Test1";
        tTable.Rows.Add(tRow);

        tRow = tTable.NewRow();
        tRow["Column1"] = 2;
        tRow["Column2"] = "Test2";
        tTable.Rows.Add(tRow);

        tRow = tTable.NewRow();
        tRow["Column1"] = 3;
        tRow["Column2"] = "Test3";
        tTable.Rows.Add(tRow);

        tRow = tTable.NewRow();
        tRow["Column1"] = 4;
        tRow["Column2"] = "Test4";
        tTable.Rows.Add(tRow);

        tRow = tTable.NewRow();
        tRow["Column1"] = 5;
        tRow["Column2"] = "Test5";
        tTable.Rows.Add(tRow);

        return tTable;
    }

    private void BindData()
    {
        DataTable tTable = GetData();

        TestGrid.DataSource = tTable;
        TestGrid.DataBind();

        if (!String.IsNullOrEmpty(Request.QueryString["edit"]))
        {
            foreach (DataGridItem tRow in TestGrid.Items)
            {
                if (tRow.Cells[0].Text == Request.QueryString["edit"])
                    TestGrid.EditItemIndex = tRow.ItemIndex;
            }
            TestGrid.DataBind();
        }
    }

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

你应该能够启动它(显然是将数据网格添加到ASPX中)然后在URL的末尾放置?edit =以使其在编辑模式下打开相关条目。

答案 1 :(得分:2)

首先,非常感谢史蒂夫罗宾斯让我开始走上正轨。我的方法略有不同,部分原因是我没有使用DataBind方法。

我使用DataView的OnRowDataBound和OnDataBound事件的组合。 OnRowDataBound事件,用于确定要进入编辑模式的行的索引。 OnDataBound事件设置索引并重新绑定DataView。

变量用于确保View不会连续反弹。

以下是为简洁起见而编辑的aspx页面的关键。

<asp:GridView ID="GridView1" runat="server" 
              DataSourceID="CreativeTypeDS"
              AutoGenerateColumns="False" 
              DataKeyNames="SourceCreativeTypeID" 
              EmptyDataText="No Cretive Types at this time."
              CellPadding="3" CellSpacing="1"
              OnRowDataBound="GridView1_RowDataBound"
              OnDataBound="GridView1_DataBound" >
        <Columns>
           [Template Columns Here]
        </Columns>
</asp:GridView>

<asp:SqlDataSource ID="CreativeTypeDS" runat="server" 
                   SelectCommand="cmsSourceCreativeTypeSel"
                   SelectCommandType="StoredProcedure" 
           UpdateCommand="cmsSourceCreativeTypeUpd"
                   UpdateCommandType="StoredProcedure">
    <SelectParameters>                
       <asp:Parameter Name="Active" DefaultValue="0" />
    </SelectParameters>
    <UpdateParameters>
       <asp:Parameter Name="SourceCreativeTypeID" Type="Int32" />
       <asp:Parameter Name="SourceCategoryID" Type="Int32"/>
       <asp:Parameter Name="Name" Type="String" />
       <asp:Parameter Name="Active" Type="Boolean" />
     </UpdateParameters>
</asp:SqlDataSource>

现在为后面的代码。

 public partial class SourceCreativeTypes : System.Web.UI.Page
 {
    private int? EditIndex = null;
    private bool GridRebound = false;
    protected override void OnPreInit(EventArgs e)        
    {
       CreativeTypeDS.ConnectionString = "[CONNECTION STRING MAGIC HERE]";
    }

    protected void Page_Load(object sender, EventArgs e)
    {
        if (IsPostBack)
        {                
            //Dont Want to set edit row manualy if post back
            GridRebound = true;
        }
    }

    //Use the Row Databound Event to find the row to put into edit mode 
    protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (!String.IsNullOrEmpty(Request.QueryString["ID"]))
        {
            //Get Target ID from Query String
            string sSourceCreativeTypeID = Request.QueryString["ID"];
            //Get data for row being bound
            DataRowView rowView = (DataRowView)e.Row.DataItem;

            // Set index if we are in a "normal row", the row data 
            // has been retrieved
            // and the Supplied ID matches that of this row
            if ((e.Row.RowState == DataControlRowState.Normal || 
                e.Row.RowState == DataControlRowState.Alternate) 
                &&
                (rowView != null && 
                 rowView["SourceCreativeTypeID"].ToString() == sSourceCreativeTypeID)
                )
            {                   
                EditIndex = e.Row.RowIndex;                   
            }
        }
    }

    /* Use the Datbound Event to set the required row to index mode
     * Then Rebind the grid. Rebinding in Row Databound does not work
     * for Reasons unknown */
    protected void GridView1_DataBound(object sender, EventArgs e)
    {
        //Set Gridview edit index if one is supplied and page is not a post back
        if (!GridRebound && EditIndex != null)
        {
            //Setting GridRebound ensures this only happens once
            GridRebound = true;
            GridView1.EditIndex = (int)EditIndex;
            GridView1.DataBind();
        }
     }
   } 
}

希望在史蒂夫和我自己之间,我们帮助你们中的一些人