ASP.Net Gridview, How to activate Edit Mode based on ID (DataKey)

asp.netgridview

I have a page, lets call it SourceTypes.aspx, that has a a GridView that is displaying a list of Source Types. Part of the GridView is a DataKey, SourceTypeID. If source TypeID is passed to the page via a query sting, how to I put the Gridview into Edit mode for the appropriate row based on the SourceTypeID?

The GridView is bound to a SQlDataSource object.

I have a feeling I am going to kick myself when the answer appears!!

I have looked at Putting a gridview row in edit mode programmatically but it is some what lacking in specifics

Best Answer

It's a little trickier when you want to put it into edit mode based on data. You tell the datagrid which of it's displayed rows is editable, not which data you want to be editable, so you'll need to go through each of the rows in the grid, see if it matches the id, and set the EditItemIndex to the appropriate value and rebind.

You could look at the source data and get the row number from that before you bind, but then you may have problems with paging, sorting etc.

It's a bit messy having to rebind the grid, but I can't think of a better way off the top of my head.

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();
    }
}

You should be able to fire that up (with a datagrid added to the ASPX obviously) then put ?edit= on the end of the URL to get it to open the relevent entry in edit mode.

Related Topic