Data Going Out of Synch when using GridView inside UpdatePanel












2














Data in my GridView inside an UpdatePanel is going out of synch with the database and I can't figure out why. This has resulted in incorrect updates to the database which I have to fix rapidly! Can anyone help?



I have multiple UpdatePanels that have GridViews inside that can be edited by the user. There is a search feature and filter buttons that select queried data from the database and display in the GridView. There is sorting enabled and the "out of synchness" occurs mostly when sorting and then editing a field.



The data comes from a SQL Database. I can update the data directly through OnTextChange option of my TemplateField like this:



<asp:GridView 
ID="GridView4"
runat="server"
OnSorting="TaskGridView_Sorting"
AllowSorting="True"
Width="100%" >
<Columns>
<asp:TemplateField SortExpression="name" HeaderText="Name">
<HeaderStyle HorizontalAlign="Left" CssClass="col_name" />
<ItemTemplate>
<asp:TextBox ID="name" AutoPostBack="True" CssClass="col_name" runat="server" Text='<%# Eval("name") %>' Width=180 OnTextChanged="text_change" />
</ItemTemplate>
</asp:TemplateField>
...


I have my gridview inside an UpdatePanel that has these options:



    <asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Conditional">
<ContentTemplate>
...


I have enabled partial rendering like this:



    <ajaxToolKit:ToolkitScriptManager EnablePartialRendering="true" runat="server" />


I have buttons that filter the data by requerying the database and displaying just the filtered data like this:



DataGrid_Load(DAL.Search_reg_log(OrgText.Text, searchText, searchCol), "reg");


The gridview gets its data loaded like this:



private void DataGrid_Load(DataTable command, string type)
{
DataTable dataTable = new DataTable();
dataTable = command;
string sortDir = ViewState["SortDirection"] as string;
string sortExp = ViewState["SortExpression"] as string;

if(ViewState["SortExpression"] != null)
{
dataTable = resort(dataTable, sortExp, sortDir);
}

try
{
var query = from c in dataTable.AsEnumerable()
where c.Field<string>("status") == "Invoiced" && c.Field<string>("reg_cat_id") != "Archive"
|| c.Field<string>("status") == "Confirmed" && c.Field<string>("reg_cat_id") != "Archive"
select c ;

if(query.Any()){
DataTable t2 = query.CopyToDataTable();
GridView4.DataSource = t2;
GridView4.DataBind();
} else {
GridView4.DataSource = new DataTable();
GridView4.DataBind();
}
}
catch(Exception e) {
ErrorText.Text = "Caught Exception: " + e;
}

...


I have isolated one cause of the data errors which occurs after sorting a column and then



protected void TaskGridView_Sorting(object sender, GridViewSortEventArgs e)
{
string sortExp = ViewState["SortExpression"] as string;
string sortDir = ViewState["SortDirection"] as string;
if(sortDir == "asc" & sortExp == e.SortExpression.ToString())
ViewState["SortDirection"] = "desc";
else
ViewState["SortDirection"] = "asc";
ViewState["SortExpression"] = e.SortExpression.ToString();

if(searchCol != "" && searchText != "")
DataGrid_Load(DAL.Search_reg_log(OrgText.Text, searchText, searchCol), "reg");
else
DataGrid_Load(DAL.reg_log(HeadText.Text, OrgText.Text), "reg");

UpdatePanels();

}


Here is the resort function:



public static DataTable resort(DataTable dt, string colName, string direction)
{
dt.DefaultView.Sort = colName + " " + direction;
dt = dt.DefaultView.ToTable();
return dt;
}


Please help with some direction of what might be causing this.










share|improve this question
























  • Anyone interested in the bounty?
    – jroyce
    Nov 27 at 0:21
















2














Data in my GridView inside an UpdatePanel is going out of synch with the database and I can't figure out why. This has resulted in incorrect updates to the database which I have to fix rapidly! Can anyone help?



I have multiple UpdatePanels that have GridViews inside that can be edited by the user. There is a search feature and filter buttons that select queried data from the database and display in the GridView. There is sorting enabled and the "out of synchness" occurs mostly when sorting and then editing a field.



The data comes from a SQL Database. I can update the data directly through OnTextChange option of my TemplateField like this:



<asp:GridView 
ID="GridView4"
runat="server"
OnSorting="TaskGridView_Sorting"
AllowSorting="True"
Width="100%" >
<Columns>
<asp:TemplateField SortExpression="name" HeaderText="Name">
<HeaderStyle HorizontalAlign="Left" CssClass="col_name" />
<ItemTemplate>
<asp:TextBox ID="name" AutoPostBack="True" CssClass="col_name" runat="server" Text='<%# Eval("name") %>' Width=180 OnTextChanged="text_change" />
</ItemTemplate>
</asp:TemplateField>
...


I have my gridview inside an UpdatePanel that has these options:



    <asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Conditional">
<ContentTemplate>
...


I have enabled partial rendering like this:



    <ajaxToolKit:ToolkitScriptManager EnablePartialRendering="true" runat="server" />


I have buttons that filter the data by requerying the database and displaying just the filtered data like this:



DataGrid_Load(DAL.Search_reg_log(OrgText.Text, searchText, searchCol), "reg");


The gridview gets its data loaded like this:



private void DataGrid_Load(DataTable command, string type)
{
DataTable dataTable = new DataTable();
dataTable = command;
string sortDir = ViewState["SortDirection"] as string;
string sortExp = ViewState["SortExpression"] as string;

if(ViewState["SortExpression"] != null)
{
dataTable = resort(dataTable, sortExp, sortDir);
}

try
{
var query = from c in dataTable.AsEnumerable()
where c.Field<string>("status") == "Invoiced" && c.Field<string>("reg_cat_id") != "Archive"
|| c.Field<string>("status") == "Confirmed" && c.Field<string>("reg_cat_id") != "Archive"
select c ;

if(query.Any()){
DataTable t2 = query.CopyToDataTable();
GridView4.DataSource = t2;
GridView4.DataBind();
} else {
GridView4.DataSource = new DataTable();
GridView4.DataBind();
}
}
catch(Exception e) {
ErrorText.Text = "Caught Exception: " + e;
}

...


I have isolated one cause of the data errors which occurs after sorting a column and then



protected void TaskGridView_Sorting(object sender, GridViewSortEventArgs e)
{
string sortExp = ViewState["SortExpression"] as string;
string sortDir = ViewState["SortDirection"] as string;
if(sortDir == "asc" & sortExp == e.SortExpression.ToString())
ViewState["SortDirection"] = "desc";
else
ViewState["SortDirection"] = "asc";
ViewState["SortExpression"] = e.SortExpression.ToString();

if(searchCol != "" && searchText != "")
DataGrid_Load(DAL.Search_reg_log(OrgText.Text, searchText, searchCol), "reg");
else
DataGrid_Load(DAL.reg_log(HeadText.Text, OrgText.Text), "reg");

UpdatePanels();

}


Here is the resort function:



public static DataTable resort(DataTable dt, string colName, string direction)
{
dt.DefaultView.Sort = colName + " " + direction;
dt = dt.DefaultView.ToTable();
return dt;
}


Please help with some direction of what might be causing this.










share|improve this question
























  • Anyone interested in the bounty?
    – jroyce
    Nov 27 at 0:21














2












2








2







Data in my GridView inside an UpdatePanel is going out of synch with the database and I can't figure out why. This has resulted in incorrect updates to the database which I have to fix rapidly! Can anyone help?



I have multiple UpdatePanels that have GridViews inside that can be edited by the user. There is a search feature and filter buttons that select queried data from the database and display in the GridView. There is sorting enabled and the "out of synchness" occurs mostly when sorting and then editing a field.



The data comes from a SQL Database. I can update the data directly through OnTextChange option of my TemplateField like this:



<asp:GridView 
ID="GridView4"
runat="server"
OnSorting="TaskGridView_Sorting"
AllowSorting="True"
Width="100%" >
<Columns>
<asp:TemplateField SortExpression="name" HeaderText="Name">
<HeaderStyle HorizontalAlign="Left" CssClass="col_name" />
<ItemTemplate>
<asp:TextBox ID="name" AutoPostBack="True" CssClass="col_name" runat="server" Text='<%# Eval("name") %>' Width=180 OnTextChanged="text_change" />
</ItemTemplate>
</asp:TemplateField>
...


I have my gridview inside an UpdatePanel that has these options:



    <asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Conditional">
<ContentTemplate>
...


I have enabled partial rendering like this:



    <ajaxToolKit:ToolkitScriptManager EnablePartialRendering="true" runat="server" />


I have buttons that filter the data by requerying the database and displaying just the filtered data like this:



DataGrid_Load(DAL.Search_reg_log(OrgText.Text, searchText, searchCol), "reg");


The gridview gets its data loaded like this:



private void DataGrid_Load(DataTable command, string type)
{
DataTable dataTable = new DataTable();
dataTable = command;
string sortDir = ViewState["SortDirection"] as string;
string sortExp = ViewState["SortExpression"] as string;

if(ViewState["SortExpression"] != null)
{
dataTable = resort(dataTable, sortExp, sortDir);
}

try
{
var query = from c in dataTable.AsEnumerable()
where c.Field<string>("status") == "Invoiced" && c.Field<string>("reg_cat_id") != "Archive"
|| c.Field<string>("status") == "Confirmed" && c.Field<string>("reg_cat_id") != "Archive"
select c ;

if(query.Any()){
DataTable t2 = query.CopyToDataTable();
GridView4.DataSource = t2;
GridView4.DataBind();
} else {
GridView4.DataSource = new DataTable();
GridView4.DataBind();
}
}
catch(Exception e) {
ErrorText.Text = "Caught Exception: " + e;
}

...


I have isolated one cause of the data errors which occurs after sorting a column and then



protected void TaskGridView_Sorting(object sender, GridViewSortEventArgs e)
{
string sortExp = ViewState["SortExpression"] as string;
string sortDir = ViewState["SortDirection"] as string;
if(sortDir == "asc" & sortExp == e.SortExpression.ToString())
ViewState["SortDirection"] = "desc";
else
ViewState["SortDirection"] = "asc";
ViewState["SortExpression"] = e.SortExpression.ToString();

if(searchCol != "" && searchText != "")
DataGrid_Load(DAL.Search_reg_log(OrgText.Text, searchText, searchCol), "reg");
else
DataGrid_Load(DAL.reg_log(HeadText.Text, OrgText.Text), "reg");

UpdatePanels();

}


Here is the resort function:



public static DataTable resort(DataTable dt, string colName, string direction)
{
dt.DefaultView.Sort = colName + " " + direction;
dt = dt.DefaultView.ToTable();
return dt;
}


Please help with some direction of what might be causing this.










share|improve this question















Data in my GridView inside an UpdatePanel is going out of synch with the database and I can't figure out why. This has resulted in incorrect updates to the database which I have to fix rapidly! Can anyone help?



I have multiple UpdatePanels that have GridViews inside that can be edited by the user. There is a search feature and filter buttons that select queried data from the database and display in the GridView. There is sorting enabled and the "out of synchness" occurs mostly when sorting and then editing a field.



The data comes from a SQL Database. I can update the data directly through OnTextChange option of my TemplateField like this:



<asp:GridView 
ID="GridView4"
runat="server"
OnSorting="TaskGridView_Sorting"
AllowSorting="True"
Width="100%" >
<Columns>
<asp:TemplateField SortExpression="name" HeaderText="Name">
<HeaderStyle HorizontalAlign="Left" CssClass="col_name" />
<ItemTemplate>
<asp:TextBox ID="name" AutoPostBack="True" CssClass="col_name" runat="server" Text='<%# Eval("name") %>' Width=180 OnTextChanged="text_change" />
</ItemTemplate>
</asp:TemplateField>
...


I have my gridview inside an UpdatePanel that has these options:



    <asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Conditional">
<ContentTemplate>
...


I have enabled partial rendering like this:



    <ajaxToolKit:ToolkitScriptManager EnablePartialRendering="true" runat="server" />


I have buttons that filter the data by requerying the database and displaying just the filtered data like this:



DataGrid_Load(DAL.Search_reg_log(OrgText.Text, searchText, searchCol), "reg");


The gridview gets its data loaded like this:



private void DataGrid_Load(DataTable command, string type)
{
DataTable dataTable = new DataTable();
dataTable = command;
string sortDir = ViewState["SortDirection"] as string;
string sortExp = ViewState["SortExpression"] as string;

if(ViewState["SortExpression"] != null)
{
dataTable = resort(dataTable, sortExp, sortDir);
}

try
{
var query = from c in dataTable.AsEnumerable()
where c.Field<string>("status") == "Invoiced" && c.Field<string>("reg_cat_id") != "Archive"
|| c.Field<string>("status") == "Confirmed" && c.Field<string>("reg_cat_id") != "Archive"
select c ;

if(query.Any()){
DataTable t2 = query.CopyToDataTable();
GridView4.DataSource = t2;
GridView4.DataBind();
} else {
GridView4.DataSource = new DataTable();
GridView4.DataBind();
}
}
catch(Exception e) {
ErrorText.Text = "Caught Exception: " + e;
}

...


I have isolated one cause of the data errors which occurs after sorting a column and then



protected void TaskGridView_Sorting(object sender, GridViewSortEventArgs e)
{
string sortExp = ViewState["SortExpression"] as string;
string sortDir = ViewState["SortDirection"] as string;
if(sortDir == "asc" & sortExp == e.SortExpression.ToString())
ViewState["SortDirection"] = "desc";
else
ViewState["SortDirection"] = "asc";
ViewState["SortExpression"] = e.SortExpression.ToString();

if(searchCol != "" && searchText != "")
DataGrid_Load(DAL.Search_reg_log(OrgText.Text, searchText, searchCol), "reg");
else
DataGrid_Load(DAL.reg_log(HeadText.Text, OrgText.Text), "reg");

UpdatePanels();

}


Here is the resort function:



public static DataTable resort(DataTable dt, string colName, string direction)
{
dt.DefaultView.Sort = colName + " " + direction;
dt = dt.DefaultView.ToTable();
return dt;
}


Please help with some direction of what might be causing this.







asp.net gridview updatepanel






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Dec 2 at 20:50

























asked Nov 22 at 22:18









jroyce

1,48121537




1,48121537












  • Anyone interested in the bounty?
    – jroyce
    Nov 27 at 0:21


















  • Anyone interested in the bounty?
    – jroyce
    Nov 27 at 0:21
















Anyone interested in the bounty?
– jroyce
Nov 27 at 0:21




Anyone interested in the bounty?
– jroyce
Nov 27 at 0:21












1 Answer
1






active

oldest

votes


















3





+50









It looks like you are having some trouble with GridView and updating them. I will post a complete working example below. Start with that and gradually update that code to fit your own needs, like getting data with var query = from c in dataTable.AsEnumerable(). The important thing is to sort the data every time you (re)bind the GridView data. And I'm not sure what is happening inside resort, but you have to use dt.DefaultView.ToTable(); to save the sorting in the DataTable.



<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>

<asp:GridView ID="GridView1" runat="server"
DataKeyNames="ID" AllowSorting="true"
OnSorting="GridView1_Sorting"
AutoGenerateColumns="false"
AutoGenerateEditButton="true"
OnRowEditing="GridView1_RowEditing"
OnRowCancelingEdit="GridView1_RowCancelingEdit"
OnRowUpdating="GridView1_RowUpdating">
<Columns>

<asp:TemplateField HeaderText="ID" SortExpression="ID">
<ItemTemplate>
<%# Eval("ID") %>
</ItemTemplate>
</asp:TemplateField>

<asp:TemplateField HeaderText="Name" SortExpression="name">
<ItemTemplate>
<%# Eval("name") %>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="TextBox1" runat="server" Text=' <%# Eval("name") %>'></asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>

</Columns>
</asp:GridView>

<asp:Literal ID="Literal1" runat="server"></asp:Literal>

</ContentTemplate>
</asp:UpdatePanel>


Code behind



protected void Page_Load(object sender, EventArgs e)
{
//bind data in an ispostback check
if (!IsPostBack)
{
DataGrid_Load();
}
}


private void DataGrid_Load()
{
//load the datatable data
DataTable dt = source;

//check if the viewsstate existst
if (ViewState["SortExpression"] != null && ViewState["SortDirection"] != null)
{
//sort the datatable before binding it to the gridview
dt.DefaultView.Sort = ViewState["SortExpression"] + " " + ViewState["SortDirection"];
dt.DefaultView.ToTable();
}

//bind the sorted datatable to the gridvidw
GridView1.DataSource = dt;
GridView1.DataBind();
}


protected void GridView1_Sorting(object sender, GridViewSortEventArgs e)
{
//load the previous sorting settigns
string sortExp = ViewState["SortExpression"] as string;
string sortDir = ViewState["SortDirection"] as string;

//reverse the direction if the column is the same as the previous sort
if (sortDir == "asc" & sortExp == e.SortExpression.ToString())
ViewState["SortDirection"] = "desc";
else
ViewState["SortDirection"] = "asc";

//put the current sort column in the viewstate
ViewState["SortExpression"] = e.SortExpression.ToString();

//rebind data
DataGrid_Load();
}


protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
{
//set the edit index and rebind data
GridView1.EditIndex = e.NewEditIndex;
DataGrid_Load();
}


protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
//reset the edit index and rebind data
GridView1.EditIndex = -1;
DataGrid_Load();
}


protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
//use findcontrol to locate the textbox in the edit template
TextBox tb = (TextBox)GridView1.Rows[e.RowIndex].FindControl("TextBox1");

//get the id of the row from the datakeys
int id = Convert.ToInt32(GridView1.DataKeys[e.RowIndex].Values[0]);

//show result for testing
Literal1.Text = "ID: " + id + "<br>Name: " + tb.Text;

//reset the edit index and rebind data
GridView1_RowCancelingEdit(null, null);
}





share|improve this answer





















  • Thank for this detailed answer. If I have several gridviews is it correct that I load all of them from within my DataGrid_Load function? Or should they each have a separate load function?
    – jroyce
    Nov 27 at 9:45






  • 1




    It is better to load them separately, it saves some overhead. And depending on how you are fetching data, it could save some database queries.
    – VDWWD
    Nov 27 at 9:47










  • Ok so best would be separate dataGrid1_Load, dataGrid2_Load l, etc.
    – jroyce
    Nov 27 at 10:02






  • 1




    Yes, then you can call that method from somewhere else also if needed.
    – VDWWD
    Nov 27 at 10:03






  • 1




    If you're not re-binding the updated data to the grid view in your OnTextChanged="text_change" event, that's likely the issue. Despite the change of value in the textbox, and in the database, the page will probably have retained the old values in the ViewState. This will be restored to the page, instead of the new value.
    – JonLord
    Dec 1 at 1:16













Your Answer






StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");

StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);

StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});

function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});


}
});














draft saved

draft discarded


















StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53438582%2fdata-going-out-of-synch-when-using-gridview-inside-updatepanel%23new-answer', 'question_page');
}
);

Post as a guest















Required, but never shown

























1 Answer
1






active

oldest

votes








1 Answer
1






active

oldest

votes









active

oldest

votes






active

oldest

votes









3





+50









It looks like you are having some trouble with GridView and updating them. I will post a complete working example below. Start with that and gradually update that code to fit your own needs, like getting data with var query = from c in dataTable.AsEnumerable(). The important thing is to sort the data every time you (re)bind the GridView data. And I'm not sure what is happening inside resort, but you have to use dt.DefaultView.ToTable(); to save the sorting in the DataTable.



<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>

<asp:GridView ID="GridView1" runat="server"
DataKeyNames="ID" AllowSorting="true"
OnSorting="GridView1_Sorting"
AutoGenerateColumns="false"
AutoGenerateEditButton="true"
OnRowEditing="GridView1_RowEditing"
OnRowCancelingEdit="GridView1_RowCancelingEdit"
OnRowUpdating="GridView1_RowUpdating">
<Columns>

<asp:TemplateField HeaderText="ID" SortExpression="ID">
<ItemTemplate>
<%# Eval("ID") %>
</ItemTemplate>
</asp:TemplateField>

<asp:TemplateField HeaderText="Name" SortExpression="name">
<ItemTemplate>
<%# Eval("name") %>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="TextBox1" runat="server" Text=' <%# Eval("name") %>'></asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>

</Columns>
</asp:GridView>

<asp:Literal ID="Literal1" runat="server"></asp:Literal>

</ContentTemplate>
</asp:UpdatePanel>


Code behind



protected void Page_Load(object sender, EventArgs e)
{
//bind data in an ispostback check
if (!IsPostBack)
{
DataGrid_Load();
}
}


private void DataGrid_Load()
{
//load the datatable data
DataTable dt = source;

//check if the viewsstate existst
if (ViewState["SortExpression"] != null && ViewState["SortDirection"] != null)
{
//sort the datatable before binding it to the gridview
dt.DefaultView.Sort = ViewState["SortExpression"] + " " + ViewState["SortDirection"];
dt.DefaultView.ToTable();
}

//bind the sorted datatable to the gridvidw
GridView1.DataSource = dt;
GridView1.DataBind();
}


protected void GridView1_Sorting(object sender, GridViewSortEventArgs e)
{
//load the previous sorting settigns
string sortExp = ViewState["SortExpression"] as string;
string sortDir = ViewState["SortDirection"] as string;

//reverse the direction if the column is the same as the previous sort
if (sortDir == "asc" & sortExp == e.SortExpression.ToString())
ViewState["SortDirection"] = "desc";
else
ViewState["SortDirection"] = "asc";

//put the current sort column in the viewstate
ViewState["SortExpression"] = e.SortExpression.ToString();

//rebind data
DataGrid_Load();
}


protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
{
//set the edit index and rebind data
GridView1.EditIndex = e.NewEditIndex;
DataGrid_Load();
}


protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
//reset the edit index and rebind data
GridView1.EditIndex = -1;
DataGrid_Load();
}


protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
//use findcontrol to locate the textbox in the edit template
TextBox tb = (TextBox)GridView1.Rows[e.RowIndex].FindControl("TextBox1");

//get the id of the row from the datakeys
int id = Convert.ToInt32(GridView1.DataKeys[e.RowIndex].Values[0]);

//show result for testing
Literal1.Text = "ID: " + id + "<br>Name: " + tb.Text;

//reset the edit index and rebind data
GridView1_RowCancelingEdit(null, null);
}





share|improve this answer





















  • Thank for this detailed answer. If I have several gridviews is it correct that I load all of them from within my DataGrid_Load function? Or should they each have a separate load function?
    – jroyce
    Nov 27 at 9:45






  • 1




    It is better to load them separately, it saves some overhead. And depending on how you are fetching data, it could save some database queries.
    – VDWWD
    Nov 27 at 9:47










  • Ok so best would be separate dataGrid1_Load, dataGrid2_Load l, etc.
    – jroyce
    Nov 27 at 10:02






  • 1




    Yes, then you can call that method from somewhere else also if needed.
    – VDWWD
    Nov 27 at 10:03






  • 1




    If you're not re-binding the updated data to the grid view in your OnTextChanged="text_change" event, that's likely the issue. Despite the change of value in the textbox, and in the database, the page will probably have retained the old values in the ViewState. This will be restored to the page, instead of the new value.
    – JonLord
    Dec 1 at 1:16


















3





+50









It looks like you are having some trouble with GridView and updating them. I will post a complete working example below. Start with that and gradually update that code to fit your own needs, like getting data with var query = from c in dataTable.AsEnumerable(). The important thing is to sort the data every time you (re)bind the GridView data. And I'm not sure what is happening inside resort, but you have to use dt.DefaultView.ToTable(); to save the sorting in the DataTable.



<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>

<asp:GridView ID="GridView1" runat="server"
DataKeyNames="ID" AllowSorting="true"
OnSorting="GridView1_Sorting"
AutoGenerateColumns="false"
AutoGenerateEditButton="true"
OnRowEditing="GridView1_RowEditing"
OnRowCancelingEdit="GridView1_RowCancelingEdit"
OnRowUpdating="GridView1_RowUpdating">
<Columns>

<asp:TemplateField HeaderText="ID" SortExpression="ID">
<ItemTemplate>
<%# Eval("ID") %>
</ItemTemplate>
</asp:TemplateField>

<asp:TemplateField HeaderText="Name" SortExpression="name">
<ItemTemplate>
<%# Eval("name") %>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="TextBox1" runat="server" Text=' <%# Eval("name") %>'></asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>

</Columns>
</asp:GridView>

<asp:Literal ID="Literal1" runat="server"></asp:Literal>

</ContentTemplate>
</asp:UpdatePanel>


Code behind



protected void Page_Load(object sender, EventArgs e)
{
//bind data in an ispostback check
if (!IsPostBack)
{
DataGrid_Load();
}
}


private void DataGrid_Load()
{
//load the datatable data
DataTable dt = source;

//check if the viewsstate existst
if (ViewState["SortExpression"] != null && ViewState["SortDirection"] != null)
{
//sort the datatable before binding it to the gridview
dt.DefaultView.Sort = ViewState["SortExpression"] + " " + ViewState["SortDirection"];
dt.DefaultView.ToTable();
}

//bind the sorted datatable to the gridvidw
GridView1.DataSource = dt;
GridView1.DataBind();
}


protected void GridView1_Sorting(object sender, GridViewSortEventArgs e)
{
//load the previous sorting settigns
string sortExp = ViewState["SortExpression"] as string;
string sortDir = ViewState["SortDirection"] as string;

//reverse the direction if the column is the same as the previous sort
if (sortDir == "asc" & sortExp == e.SortExpression.ToString())
ViewState["SortDirection"] = "desc";
else
ViewState["SortDirection"] = "asc";

//put the current sort column in the viewstate
ViewState["SortExpression"] = e.SortExpression.ToString();

//rebind data
DataGrid_Load();
}


protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
{
//set the edit index and rebind data
GridView1.EditIndex = e.NewEditIndex;
DataGrid_Load();
}


protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
//reset the edit index and rebind data
GridView1.EditIndex = -1;
DataGrid_Load();
}


protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
//use findcontrol to locate the textbox in the edit template
TextBox tb = (TextBox)GridView1.Rows[e.RowIndex].FindControl("TextBox1");

//get the id of the row from the datakeys
int id = Convert.ToInt32(GridView1.DataKeys[e.RowIndex].Values[0]);

//show result for testing
Literal1.Text = "ID: " + id + "<br>Name: " + tb.Text;

//reset the edit index and rebind data
GridView1_RowCancelingEdit(null, null);
}





share|improve this answer





















  • Thank for this detailed answer. If I have several gridviews is it correct that I load all of them from within my DataGrid_Load function? Or should they each have a separate load function?
    – jroyce
    Nov 27 at 9:45






  • 1




    It is better to load them separately, it saves some overhead. And depending on how you are fetching data, it could save some database queries.
    – VDWWD
    Nov 27 at 9:47










  • Ok so best would be separate dataGrid1_Load, dataGrid2_Load l, etc.
    – jroyce
    Nov 27 at 10:02






  • 1




    Yes, then you can call that method from somewhere else also if needed.
    – VDWWD
    Nov 27 at 10:03






  • 1




    If you're not re-binding the updated data to the grid view in your OnTextChanged="text_change" event, that's likely the issue. Despite the change of value in the textbox, and in the database, the page will probably have retained the old values in the ViewState. This will be restored to the page, instead of the new value.
    – JonLord
    Dec 1 at 1:16
















3





+50







3





+50



3




+50




It looks like you are having some trouble with GridView and updating them. I will post a complete working example below. Start with that and gradually update that code to fit your own needs, like getting data with var query = from c in dataTable.AsEnumerable(). The important thing is to sort the data every time you (re)bind the GridView data. And I'm not sure what is happening inside resort, but you have to use dt.DefaultView.ToTable(); to save the sorting in the DataTable.



<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>

<asp:GridView ID="GridView1" runat="server"
DataKeyNames="ID" AllowSorting="true"
OnSorting="GridView1_Sorting"
AutoGenerateColumns="false"
AutoGenerateEditButton="true"
OnRowEditing="GridView1_RowEditing"
OnRowCancelingEdit="GridView1_RowCancelingEdit"
OnRowUpdating="GridView1_RowUpdating">
<Columns>

<asp:TemplateField HeaderText="ID" SortExpression="ID">
<ItemTemplate>
<%# Eval("ID") %>
</ItemTemplate>
</asp:TemplateField>

<asp:TemplateField HeaderText="Name" SortExpression="name">
<ItemTemplate>
<%# Eval("name") %>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="TextBox1" runat="server" Text=' <%# Eval("name") %>'></asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>

</Columns>
</asp:GridView>

<asp:Literal ID="Literal1" runat="server"></asp:Literal>

</ContentTemplate>
</asp:UpdatePanel>


Code behind



protected void Page_Load(object sender, EventArgs e)
{
//bind data in an ispostback check
if (!IsPostBack)
{
DataGrid_Load();
}
}


private void DataGrid_Load()
{
//load the datatable data
DataTable dt = source;

//check if the viewsstate existst
if (ViewState["SortExpression"] != null && ViewState["SortDirection"] != null)
{
//sort the datatable before binding it to the gridview
dt.DefaultView.Sort = ViewState["SortExpression"] + " " + ViewState["SortDirection"];
dt.DefaultView.ToTable();
}

//bind the sorted datatable to the gridvidw
GridView1.DataSource = dt;
GridView1.DataBind();
}


protected void GridView1_Sorting(object sender, GridViewSortEventArgs e)
{
//load the previous sorting settigns
string sortExp = ViewState["SortExpression"] as string;
string sortDir = ViewState["SortDirection"] as string;

//reverse the direction if the column is the same as the previous sort
if (sortDir == "asc" & sortExp == e.SortExpression.ToString())
ViewState["SortDirection"] = "desc";
else
ViewState["SortDirection"] = "asc";

//put the current sort column in the viewstate
ViewState["SortExpression"] = e.SortExpression.ToString();

//rebind data
DataGrid_Load();
}


protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
{
//set the edit index and rebind data
GridView1.EditIndex = e.NewEditIndex;
DataGrid_Load();
}


protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
//reset the edit index and rebind data
GridView1.EditIndex = -1;
DataGrid_Load();
}


protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
//use findcontrol to locate the textbox in the edit template
TextBox tb = (TextBox)GridView1.Rows[e.RowIndex].FindControl("TextBox1");

//get the id of the row from the datakeys
int id = Convert.ToInt32(GridView1.DataKeys[e.RowIndex].Values[0]);

//show result for testing
Literal1.Text = "ID: " + id + "<br>Name: " + tb.Text;

//reset the edit index and rebind data
GridView1_RowCancelingEdit(null, null);
}





share|improve this answer












It looks like you are having some trouble with GridView and updating them. I will post a complete working example below. Start with that and gradually update that code to fit your own needs, like getting data with var query = from c in dataTable.AsEnumerable(). The important thing is to sort the data every time you (re)bind the GridView data. And I'm not sure what is happening inside resort, but you have to use dt.DefaultView.ToTable(); to save the sorting in the DataTable.



<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>

<asp:GridView ID="GridView1" runat="server"
DataKeyNames="ID" AllowSorting="true"
OnSorting="GridView1_Sorting"
AutoGenerateColumns="false"
AutoGenerateEditButton="true"
OnRowEditing="GridView1_RowEditing"
OnRowCancelingEdit="GridView1_RowCancelingEdit"
OnRowUpdating="GridView1_RowUpdating">
<Columns>

<asp:TemplateField HeaderText="ID" SortExpression="ID">
<ItemTemplate>
<%# Eval("ID") %>
</ItemTemplate>
</asp:TemplateField>

<asp:TemplateField HeaderText="Name" SortExpression="name">
<ItemTemplate>
<%# Eval("name") %>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="TextBox1" runat="server" Text=' <%# Eval("name") %>'></asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>

</Columns>
</asp:GridView>

<asp:Literal ID="Literal1" runat="server"></asp:Literal>

</ContentTemplate>
</asp:UpdatePanel>


Code behind



protected void Page_Load(object sender, EventArgs e)
{
//bind data in an ispostback check
if (!IsPostBack)
{
DataGrid_Load();
}
}


private void DataGrid_Load()
{
//load the datatable data
DataTable dt = source;

//check if the viewsstate existst
if (ViewState["SortExpression"] != null && ViewState["SortDirection"] != null)
{
//sort the datatable before binding it to the gridview
dt.DefaultView.Sort = ViewState["SortExpression"] + " " + ViewState["SortDirection"];
dt.DefaultView.ToTable();
}

//bind the sorted datatable to the gridvidw
GridView1.DataSource = dt;
GridView1.DataBind();
}


protected void GridView1_Sorting(object sender, GridViewSortEventArgs e)
{
//load the previous sorting settigns
string sortExp = ViewState["SortExpression"] as string;
string sortDir = ViewState["SortDirection"] as string;

//reverse the direction if the column is the same as the previous sort
if (sortDir == "asc" & sortExp == e.SortExpression.ToString())
ViewState["SortDirection"] = "desc";
else
ViewState["SortDirection"] = "asc";

//put the current sort column in the viewstate
ViewState["SortExpression"] = e.SortExpression.ToString();

//rebind data
DataGrid_Load();
}


protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
{
//set the edit index and rebind data
GridView1.EditIndex = e.NewEditIndex;
DataGrid_Load();
}


protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
//reset the edit index and rebind data
GridView1.EditIndex = -1;
DataGrid_Load();
}


protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
//use findcontrol to locate the textbox in the edit template
TextBox tb = (TextBox)GridView1.Rows[e.RowIndex].FindControl("TextBox1");

//get the id of the row from the datakeys
int id = Convert.ToInt32(GridView1.DataKeys[e.RowIndex].Values[0]);

//show result for testing
Literal1.Text = "ID: " + id + "<br>Name: " + tb.Text;

//reset the edit index and rebind data
GridView1_RowCancelingEdit(null, null);
}






share|improve this answer












share|improve this answer



share|improve this answer










answered Nov 27 at 8:25









VDWWD

22.8k113351




22.8k113351












  • Thank for this detailed answer. If I have several gridviews is it correct that I load all of them from within my DataGrid_Load function? Or should they each have a separate load function?
    – jroyce
    Nov 27 at 9:45






  • 1




    It is better to load them separately, it saves some overhead. And depending on how you are fetching data, it could save some database queries.
    – VDWWD
    Nov 27 at 9:47










  • Ok so best would be separate dataGrid1_Load, dataGrid2_Load l, etc.
    – jroyce
    Nov 27 at 10:02






  • 1




    Yes, then you can call that method from somewhere else also if needed.
    – VDWWD
    Nov 27 at 10:03






  • 1




    If you're not re-binding the updated data to the grid view in your OnTextChanged="text_change" event, that's likely the issue. Despite the change of value in the textbox, and in the database, the page will probably have retained the old values in the ViewState. This will be restored to the page, instead of the new value.
    – JonLord
    Dec 1 at 1:16




















  • Thank for this detailed answer. If I have several gridviews is it correct that I load all of them from within my DataGrid_Load function? Or should they each have a separate load function?
    – jroyce
    Nov 27 at 9:45






  • 1




    It is better to load them separately, it saves some overhead. And depending on how you are fetching data, it could save some database queries.
    – VDWWD
    Nov 27 at 9:47










  • Ok so best would be separate dataGrid1_Load, dataGrid2_Load l, etc.
    – jroyce
    Nov 27 at 10:02






  • 1




    Yes, then you can call that method from somewhere else also if needed.
    – VDWWD
    Nov 27 at 10:03






  • 1




    If you're not re-binding the updated data to the grid view in your OnTextChanged="text_change" event, that's likely the issue. Despite the change of value in the textbox, and in the database, the page will probably have retained the old values in the ViewState. This will be restored to the page, instead of the new value.
    – JonLord
    Dec 1 at 1:16


















Thank for this detailed answer. If I have several gridviews is it correct that I load all of them from within my DataGrid_Load function? Or should they each have a separate load function?
– jroyce
Nov 27 at 9:45




Thank for this detailed answer. If I have several gridviews is it correct that I load all of them from within my DataGrid_Load function? Or should they each have a separate load function?
– jroyce
Nov 27 at 9:45




1




1




It is better to load them separately, it saves some overhead. And depending on how you are fetching data, it could save some database queries.
– VDWWD
Nov 27 at 9:47




It is better to load them separately, it saves some overhead. And depending on how you are fetching data, it could save some database queries.
– VDWWD
Nov 27 at 9:47












Ok so best would be separate dataGrid1_Load, dataGrid2_Load l, etc.
– jroyce
Nov 27 at 10:02




Ok so best would be separate dataGrid1_Load, dataGrid2_Load l, etc.
– jroyce
Nov 27 at 10:02




1




1




Yes, then you can call that method from somewhere else also if needed.
– VDWWD
Nov 27 at 10:03




Yes, then you can call that method from somewhere else also if needed.
– VDWWD
Nov 27 at 10:03




1




1




If you're not re-binding the updated data to the grid view in your OnTextChanged="text_change" event, that's likely the issue. Despite the change of value in the textbox, and in the database, the page will probably have retained the old values in the ViewState. This will be restored to the page, instead of the new value.
– JonLord
Dec 1 at 1:16






If you're not re-binding the updated data to the grid view in your OnTextChanged="text_change" event, that's likely the issue. Despite the change of value in the textbox, and in the database, the page will probably have retained the old values in the ViewState. This will be restored to the page, instead of the new value.
– JonLord
Dec 1 at 1:16




















draft saved

draft discarded




















































Thanks for contributing an answer to Stack Overflow!


  • Please be sure to answer the question. Provide details and share your research!

But avoid



  • Asking for help, clarification, or responding to other answers.

  • Making statements based on opinion; back them up with references or personal experience.


To learn more, see our tips on writing great answers.





Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


Please pay close attention to the following guidance:


  • Please be sure to answer the question. Provide details and share your research!

But avoid



  • Asking for help, clarification, or responding to other answers.

  • Making statements based on opinion; back them up with references or personal experience.


To learn more, see our tips on writing great answers.




draft saved


draft discarded














StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53438582%2fdata-going-out-of-synch-when-using-gridview-inside-updatepanel%23new-answer', 'question_page');
}
);

Post as a guest















Required, but never shown





















































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown

































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown







Popular posts from this blog

A CLEAN and SIMPLE way to add appendices to Table of Contents and bookmarks

Calculate evaluation metrics using cross_val_predict sklearn

Insert data from modal to MySQL (multiple modal on website)