Velocity Reviews - Computer Hardware Reviews

Velocity Reviews > Newsgroups > Programming > ASP .Net > GridView bound DataTable - how to get updates working?

Reply
Thread Tools

GridView bound DataTable - how to get updates working?

 
 
Tomasz Jastrzebski
Guest
Posts: n/a
 
      12-04-2006
Hello Everyone,



I have a GridView control bound to a plain DataTable object.

AutoGenerateEditButton is set to true, Edit button gets displayed, and
RowEditing event fires as expected.



What do I need to change so that GridView control displays textboxes while
editing and Edit button changes to Cancel button?

What do I need to do to be able to select a row? Setting
AutoGenerateSelectButton to true and defining <SelectedRowStyle> template
does not seem to be sufficient in this scenario.



Thank you,



Tomasz


 
Reply With Quote
 
 
 
 
Walter Wang [MSFT]
Guest
Posts: n/a
 
      12-05-2006
Hi Tomasz,

Whatever data source object you bind to a control, a data source view
object is created. A data source view object is a class that can perform
SELECT, INSERT, DELETE, and UPDATE operations on a bound object.

If you're binding the GridView to a SqlDataSource or an ObjectDataSource
which incorporates data source view object that fully supports these 4
operations, the GridView will automatically enable editing the data, for
example:

<asp:GridView ID="GridView1" runat="server"
AutoGenerateColumns="False" DataKeyNames="ProductID"
DataSourceID="SqlDataSource1">
<Columns>
<asp:CommandField ShowEditButton="true" />
<asp:BoundField DataField="ProductID"
HeaderText="ProductID" InsertVisible="False"
ReadOnly="True" SortExpression="ProductID" />
<asp:BoundField DataField="ProductName"
HeaderText="ProductName" SortExpression="ProductName" />
</Columns>
</asp:GridView>
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:NorthwindConnectionString %>"
SelectCommand="SELECT [ProductID], [ProductName] FROM
[Alphabetical list of products]"
UpdateCommand="Update [Alphabetical list of products] Set
[ProductName]=@ProductName Where [ProductID]=@ProductID"
>

</asp:SqlDataSource>


However, when you're directly binding to a DataTable which doesn't have a
data source view object, it will be wrapped in a dynamically created data
source view object of type ReadOnlyDataSource--an internal undocumented
class. In such scenario, the automatic editing feature is not possible. You
will have to use template column to setup the editing template and handle
the updating yourself.

Here's a short example on how to do that manually:

<asp:GridView AutoGenerateColumns="false" ID="GridView1"
runat="server" OnRowCancelingEdit="GridView1_RowCancelingEdit"
OnRowEditing="GridView1_RowEditing" OnRowUpdating="GridView1_RowUpdating">
<Columns>
<asp:CommandField ShowEditButton="true" />
<asp:BoundField HeaderText="ID" DataField="ID"
ReadOnly="true" />
<asp:TemplateField HeaderText="Name">
<ItemTemplate>
<asp:Label ID="lblName" runat="server" Text='<%#
Eval("Name") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtName" runat="server" Text='<%#
Bind("Name") %>'></asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>


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

private void BindGrid()
{
GridView1.DataSource = GetDataSource();
GridView1.DataBind();
}

protected DataTable GetDataSource()
{
const string key = "MyDataSource";
DataTable dt = Session[key] as DataTable;
if (dt == null)
{
dt = new DataTable();
dt.Columns.Add("ID", typeof(int));
dt.Columns.Add("Name", typeof(string));
dt.Rows.Add(1, "first object");
dt.Rows.Add(2, "second object");
Session[key] = dt;
}
return dt;
}
protected void GridView1_RowEditing(object sender,
GridViewEditEventArgs e)
{
GridView1.EditIndex = e.NewEditIndex;
BindGrid();
}
protected void GridView1_RowCancelingEdit(object sender,
GridViewCancelEditEventArgs e)
{
GridView1.EditIndex = -1;
BindGrid();
}
protected void GridView1_RowUpdating(object sender,
GridViewUpdateEventArgs e)
{
int id = int.Parse(GridView1.Rows[e.RowIndex].Cells[1].Text);
TextBox txtName =
GridView1.Rows[e.RowIndex].Cells[2].FindControl("txtName") as TextBox;
string newname = txtName.Text;

DataTable dt = GetDataSource();
DataRow[] rows = dt.Select("ID = " + id.ToString());
rows[0]["Name"] = newname;
GridView1.EditIndex = -1;
BindGrid();
}


You can find more information here:

#Working with GridView without using Data Source Controls
http://www.dotnetbips.com/articles/d...le.aspx?id=511

Let me know if you need further information. Thanks.


Sincerely,
Walter Wang (, remove 'online.')
Microsoft Online Community Support

==================================================
Get notification to my posts through email? Please refer to
http://msdn.microsoft.com/subscripti...ult.aspx#notif
ications. If you are using Outlook Express, please make sure you clear the
check box "Tools/Options/Read: Get 300 headers at a time" to see your reply
promptly.

Note: The MSDN Managed Newsgroup support offering is for non-urgent issues
where an initial response from the community or a Microsoft Support
Engineer within 1 business day is acceptable. Please note that each follow
up response may take approximately 2 business days as the support
professional working with you may need further investigation to reach the
most efficient resolution. The offering is not appropriate for situations
that require urgent, real-time or phone-based interactions or complex
project analysis and dump analysis issues. Issues of this nature are best
handled working with a dedicated Microsoft Support Engineer by contacting
Microsoft Customer Support Services (CSS) at
http://msdn.microsoft.com/subscripti...t/default.aspx.
==================================================

This posting is provided "AS IS" with no warranties, and confers no rights.

 
Reply With Quote
 
 
 
 
Tomasz Jastrzebski
Guest
Posts: n/a
 
      12-06-2006
Thank you Walter, I appreciate your helpful response.
Do you also, by a chance, know how to make DetailsView bound to a DataTable
work?

Tomasz


"Walter Wang [MSFT]" <> wrote in message
news:...
> Hi Tomasz,
>
> Whatever data source object you bind to a control, a data source view
> object is created. A data source view object is a class that can perform
> SELECT, INSERT, DELETE, and UPDATE operations on a bound object.
>
> If you're binding the GridView to a SqlDataSource or an ObjectDataSource
> which incorporates data source view object that fully supports these 4
> operations, the GridView will automatically enable editing the data, for
> example:
>
> <asp:GridView ID="GridView1" runat="server"
> AutoGenerateColumns="False" DataKeyNames="ProductID"
> DataSourceID="SqlDataSource1">
> <Columns>
> <asp:CommandField ShowEditButton="true" />
> <asp:BoundField DataField="ProductID"
> HeaderText="ProductID" InsertVisible="False"
> ReadOnly="True" SortExpression="ProductID" />
> <asp:BoundField DataField="ProductName"
> HeaderText="ProductName" SortExpression="ProductName" />
> </Columns>
> </asp:GridView>
> <asp:SqlDataSource ID="SqlDataSource1" runat="server"
> ConnectionString="<%$ ConnectionStrings:NorthwindConnectionString %>"
> SelectCommand="SELECT [ProductID], [ProductName] FROM
> [Alphabetical list of products]"
> UpdateCommand="Update [Alphabetical list of products] Set
> [ProductName]=@ProductName Where [ProductID]=@ProductID"
> >

> </asp:SqlDataSource>
>
>
> However, when you're directly binding to a DataTable which doesn't have a
> data source view object, it will be wrapped in a dynamically created data
> source view object of type ReadOnlyDataSource--an internal undocumented
> class. In such scenario, the automatic editing feature is not possible.
> You
> will have to use template column to setup the editing template and handle
> the updating yourself.
>
> Here's a short example on how to do that manually:
>
> <asp:GridView AutoGenerateColumns="false" ID="GridView1"
> runat="server" OnRowCancelingEdit="GridView1_RowCancelingEdit"
> OnRowEditing="GridView1_RowEditing" OnRowUpdating="GridView1_RowUpdating">
> <Columns>
> <asp:CommandField ShowEditButton="true" />
> <asp:BoundField HeaderText="ID" DataField="ID"
> ReadOnly="true" />
> <asp:TemplateField HeaderText="Name">
> <ItemTemplate>
> <asp:Label ID="lblName" runat="server" Text='<%#
> Eval("Name") %>'></asp:Label>
> </ItemTemplate>
> <EditItemTemplate>
> <asp:TextBox ID="txtName" runat="server" Text='<%#
> Bind("Name") %>'></asp:TextBox>
> </EditItemTemplate>
> </asp:TemplateField>
> </Columns>
> </asp:GridView>
>
>
> protected void Page_Load(object sender, EventArgs e)
> {
> if (!IsPostBack)
> {
> BindGrid();
> }
> }
>
> private void BindGrid()
> {
> GridView1.DataSource = GetDataSource();
> GridView1.DataBind();
> }
>
> protected DataTable GetDataSource()
> {
> const string key = "MyDataSource";
> DataTable dt = Session[key] as DataTable;
> if (dt == null)
> {
> dt = new DataTable();
> dt.Columns.Add("ID", typeof(int));
> dt.Columns.Add("Name", typeof(string));
> dt.Rows.Add(1, "first object");
> dt.Rows.Add(2, "second object");
> Session[key] = dt;
> }
> return dt;
> }
> protected void GridView1_RowEditing(object sender,
> GridViewEditEventArgs e)
> {
> GridView1.EditIndex = e.NewEditIndex;
> BindGrid();
> }
> protected void GridView1_RowCancelingEdit(object sender,
> GridViewCancelEditEventArgs e)
> {
> GridView1.EditIndex = -1;
> BindGrid();
> }
> protected void GridView1_RowUpdating(object sender,
> GridViewUpdateEventArgs e)
> {
> int id = int.Parse(GridView1.Rows[e.RowIndex].Cells[1].Text);
> TextBox txtName =
> GridView1.Rows[e.RowIndex].Cells[2].FindControl("txtName") as TextBox;
> string newname = txtName.Text;
>
> DataTable dt = GetDataSource();
> DataRow[] rows = dt.Select("ID = " + id.ToString());
> rows[0]["Name"] = newname;
> GridView1.EditIndex = -1;
> BindGrid();
> }
>
>
> You can find more information here:
>
> #Working with GridView without using Data Source Controls
> http://www.dotnetbips.com/articles/d...le.aspx?id=511
>
> Let me know if you need further information. Thanks.
>
>
> Sincerely,
> Walter Wang (, remove 'online.')
> Microsoft Online Community Support
>
> ==================================================
> Get notification to my posts through email? Please refer to
> http://msdn.microsoft.com/subscripti...ult.aspx#notif
> ications. If you are using Outlook Express, please make sure you clear the
> check box "Tools/Options/Read: Get 300 headers at a time" to see your
> reply
> promptly.
>
> Note: The MSDN Managed Newsgroup support offering is for non-urgent issues
> where an initial response from the community or a Microsoft Support
> Engineer within 1 business day is acceptable. Please note that each follow
> up response may take approximately 2 business days as the support
> professional working with you may need further investigation to reach the
> most efficient resolution. The offering is not appropriate for situations
> that require urgent, real-time or phone-based interactions or complex
> project analysis and dump analysis issues. Issues of this nature are best
> handled working with a dedicated Microsoft Support Engineer by contacting
> Microsoft Customer Support Services (CSS) at
> http://msdn.microsoft.com/subscripti...t/default.aspx.
> ==================================================
>
> This posting is provided "AS IS" with no warranties, and confers no
> rights.
>



 
Reply With Quote
 
Walter Wang [MSFT]
Guest
Posts: n/a
 
      12-06-2006
Hi Tomasz,

It should be similar to above approach. Based on above example, we can
create a DataView and apply the filter with selected row in GridView to
update the data source that is binding to the DetailsView.

Here's some example code:

<asp:GridView DataKeyNames="ID" AutoGenerateColumns="false" ID="GridView1"
runat="server"
OnRowCancelingEdit="GridView1_RowCancelingEdit"
OnRowEditing="GridView1_RowEditing"
OnRowUpdating="GridView1_RowUpdating"
OnSelectedIndexChanged="GridView1_SelectedIndexCha nged">
<Columns>
<asp:CommandField ShowEditButton="true" ShowSelectButton="true" />
<asp:BoundField HeaderText="ID" DataField="ID" ReadOnly="true" />
<asp:TemplateField HeaderText="Name">
<ItemTemplate>
<asp:Label ID="lblName" runat="server" Text='<%#
Eval("Name") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtName" runat="server" Text='<%#
Bind("Name") %>'></asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<aspetailsView AutoGenerateEditButton="true" AutoGenerateRows="false"
ID="DetailsView1"
runat="server" DataKeyNames="ID"
OnModeChanging="DetailsView1_ModeChanging"
OnItemUpdating="DetailsView1_ItemUpdating">
<Fields>
<asp:BoundField HeaderText="ID" DataField="ID" ReadOnly="true" />
<asp:TemplateField HeaderText="Name">
<ItemTemplate>
<asp:Label ID="lblName" runat="server" Text='<%#
Eval("Name") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtName" runat="server" Text='<%#
Bind("Name") %>'></asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
</Fields>
</aspetailsView>





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

private void BindGrid()
{
GridView1.DataSource = GetDataSource();
GridView1.DataBind();
}

protected DataTable GetDataSource()
{
const string key = "MyDataSource";
DataTable dt = Session[key] as DataTable;
if (dt == null)
{
dt = new DataTable();
dt.Columns.Add("ID", typeof(int));
dt.Columns.Add("Name", typeof(string));
dt.Rows.Add(1, "first object");
dt.Rows.Add(2, "second object");
Session[key] = dt;
}
return dt;
}
protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
{
GridView1.EditIndex = e.NewEditIndex;
BindGrid();
}
protected void GridView1_RowCancelingEdit(object sender,
GridViewCancelEditEventArgs e)
{
GridView1.EditIndex = -1;
BindGrid();
}
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs
e)
{
int id = int.Parse(GridView1.Rows[e.RowIndex].Cells[1].Text);
TextBox txtName =
GridView1.Rows[e.RowIndex].Cells[2].FindControl("txtName") as TextBox;
string newname = txtName.Text;

FindRowsByID(id)[0]["Name"] = newname;
GridView1.EditIndex = -1;
BindGrid();
}

private DataRow[] FindRowsByID(int id)
{
DataRow[] rows = GetDataSource().Select("ID = " + id.ToString());
return rows;
}

private DataView CreateDataViewByID(int id)
{
DataView dv = new DataView(GetDataSource());
dv.RowFilter = "ID = " + id.ToString();
return dv;
}

protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
{
BindDetailsView();
}

private void BindDetailsView()
{
int id = (int)GridView1.SelectedValue;
DetailsView1.DataSource = CreateDataViewByID(id);
DetailsView1.DataBind();
}

protected void DetailsView1_ModeChanging(object sender,
DetailsViewModeEventArgs e)
{
DetailsView1.ChangeMode(e.NewMode);
BindDetailsView();
}

protected void DetailsView1_ItemUpdating(object sender,
DetailsViewUpdateEventArgs e)
{
int id = (int)DetailsView1.DataKey[0];
TextBox txtName = DetailsView1.FindControl("txtName") as TextBox;
string newname = txtName.Text;
FindRowsByID(id)[0]["Name"] = newname;
BindGrid();
DetailsView1.ChangeMode(DetailsViewMode.ReadOnly);
BindDetailsView();
}



Regards,
Walter Wang (, remove 'online.')
Microsoft Online Community Support

==================================================
When responding to posts, please "Reply to Group" via your newsreader so
that others may learn and benefit from your issue.
==================================================

This posting is provided "AS IS" with no warranties, and confers no rights.

 
Reply With Quote
 
Walter Wang [MSFT]
Guest
Posts: n/a
 
      12-08-2006
Hi Tomasz,

This is just a quick note to check the status of this post. What do you
think of above solution on DetailsView? Please feel free to reply here if
there's anything I can help.

Regards,
Walter Wang (, remove 'online.')
Microsoft Online Community Support

==================================================
When responding to posts, please "Reply to Group" via your newsreader so
that others may learn and benefit from your issue.
==================================================

This posting is provided "AS IS" with no warranties, and confers no rights.

 
Reply With Quote
 
 
 
Reply

Thread Tools

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are Off


Similar Threads
Thread Thread Starter Forum Replies Last Post
Re: How include a large array? Edward A. Falk C Programming 1 04-04-2013 08:07 PM
DataTable Bound to GridView Control Mel ASP .Net 0 10-27-2008 07:51 PM
GridView bound to a Datatable results in runtime error on attempts topage. Options chike_oji@yahoo.com ASP .Net 2 01-29-2008 09:22 AM
Gridview bound to Datatable. Update doesn't work, need help eric.dehaan@gmail.com ASP .Net 2 02-19-2007 02:24 PM
Add Row to datatable bound to gridview inside a gridview Elmo Watson ASP .Net 0 08-17-2006 02:26 PM



Advertisments
 



1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57