You can't get a data source back out of a web control once it's been bound and rendered. Unlike applications that you may be accustomed to programming the web is stateless and it will not persist data unless you implement that by using Session
or ViewState
.
In a typical example you would have an underlying data set that you are binding to the GridView, at the same time you can store it in ViewState
. Any changes to the grid by the user need to trigger something to make changes to the underlying data set and then you rebind the control to that data set. There are other ways of doing this, but the point is that you have to track the changes.
Here's a rudimentary example of the above using ViewState
:
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
InitialDataLoad();
}
private void InitialDataLoad()
{
var dt = new DataTable();
dt.Columns.Add("SomeData");
var dr = dt.NewRow();
dr[0] = "some initial data here";
dt.Rows.Add(dr);
GridView1.DataSource = dt;
GridView1.DataBind();
ViewState["dt"] = dt;
}
protected void Button1_Click(object sender, EventArgs e)
{
// adds a row
var dt = ViewState["dt"] as DataTable;
if (dt != null)
{
var dr = dt.NewRow();
dr[0] = "some more data here";
dt.Rows.Add(dr);
GridView1.DataSource = dt;
GridView1.DataBind();
ViewState["dt"] = dt;
}
}