unable to update gridview values in .net - c#

while updating gridview record . old values only getting updated. im using bound field. getting old value while im fetching data in variable.
<asp:GridView runat="server" ID="GvLeads" AutoGenerateColumns="false" AutoGenerateEditButton="true" AutoGenerateDeleteButton="true" OnRowDeleting="GvLeads_RowDeleting" OnRowEditing="GvLeads_RowEditing" OnRowCancelingEdit="GvLeads_RowCancelingEdit" EmptyDataText="No Records Found" OnRowUpdating="GvLeads_RowUpdating" OnRowDeleted="GvLeads_RowDeleted">
<Columns>
<asp:BoundField HeaderText="Id" DataField="LeadId" />
<asp:BoundField HeaderText="Company" DataField="Companyname" />
</Columns>
</GridView >
code behind
protected void GvLeads_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
GridViewRow row = GvLeads.Rows[e.RowIndex];
String str = ((TextBox)(row.Cells[1].Controls[0])).Text;
int Leadid = Convert.ToInt32(str);
string CompanyName = ((TextBox)(row.Cells[2].Controls[0])).Text;
}

This usually happens when you are populating grid at Page_Load as soon as RowUpdating event gets called before that Page_Load event get's called which populates the grid with initial values. How to Avoid? Use !IsPostBack for this purpose
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindGrid(); // For e.g.
}
}

Related

how to get boundfield value of a gridview in rowupdating event

i want to pick the databound field value. im getting compilation error saying doesnot contain a definatin for a Cells
<asp:GridView ID="gvBankDetails" runat="server" AutoGenerateColumns="false" AutoGenerateEditButton="true" OnRowEditing="gvBankDetails_RowEditing" OnRowCancelingEdit="gvBankDetails_RowCancelingEdit" OnRowUpdating="gvBankDetails_RowUpdating">
<Columns>
<asp:BoundField HeaderText="sl no" DataField="id" />
</Columns>
</Gridview>
protected void gvBankDetails_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
string dtr = ((TextBox)gvBankDetails.Cells[0].Controls[0]).Text;
}
to get value of bound field in grid view
protected void gvBankDetails_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
string strName = ((TextBox)gvBankDetails.Rows[e.RowIndex].Cells[3].Controls[0]).Text;
}
gvBankDetails.Rows[e.RowIndex].Cells[0].Text
index may be different based on column number

DetailsView - Values not changing in ItemUpdating

I have DetailsView binded to one object. When ItemUpdating is called (when I click update) OldValues is empty and NewValues contains old values (are the same as before update).
<asp:DetailsView ID="CustomerDetailsView" runat="server"
DefaultMode="Edit"
AutoGenerateRows="false"
OnItemUpdating="CustomerDetailsView_ItemUpdating"
>
<Fields>
<asp:BoundField DataField="LastName" HeaderText="Last name" ReadOnly="True" />
<asp:BoundField DataField="FirstName" HeaderText="First name" ReadOnly="True" />
<%-- Other fields ... --%>
<asp:CommandField ShowEditButton="true" />
</Fields>
</asp:DetailsView>
Code behind:
private Customer customer;
protected void Page_Load(object sender, EventArgs e)
{
using (var context = new CustomersContext())
{
customer = context.Logins.First();
}
CustomerDetailsView.DataSource = new List<Customer>() { customer };
CustomerDetailsView.DataBind();
}
protected void CustomerDetailsView_ItemUpdating(object sender, DetailsViewUpdateEventArgs e)
{
// e.OldValues.Count == 0
// e.NewValues["FirstName"] - is same as taken from database
}
See this answer: OldValues collection in event "ItemUpdating" of DetailsView is always empty
It appears that this only works if you use the DataSourceID property bound to a data source control.
Stupid me, I was setting new DataSource every time the page was reloaded even if it was post-back.
Should be:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
using (var context = new CustomersContext())
{
customer = context.Logins.First();
}
CustomerDetailsView.DataSource = new List<Customer>() { customer };
CustomerDetailsView.DataBind();
}
}
Can't see OldValues but NewValues looks correct.

Programmatically Add Control To DataGrid

I am trying to find the last row of my grid, and programmatically add a drop down list to the grid. My code compiles with no issues, but my RowDataBound is never hit when stepping through the code causing the list to never be added. What have I improperly coded?
EDIT
The page loads and you select an option from the drop down list. RefreshdatagridTest is called at that point.
End Of Edit
ASP Code
<div class="CenterGrid">
<asp:DataGrid runat="server" ID="datagridTest" AutoGenerateColumns="false"
Width="500px" CssClass="DataGrids" HorizontalAlign="Center" GridLines="Both"
ShowFooter="true" OnSelectedIndexChanged="datagridTest_SelectedIndexChanged"
OnItemCommand="datagridTest_ItemCommand" RowDataBound="datagridTest_RowDataBound" Visible="true">
<ItemStyle CssClass="row" />
<FooterStyle CssClass="DataGridFooters" />
<HeaderStyle CssClass="DataGridHeaders" />
<Columns>
<asp:BoundColumn DataField="Firefly" HeaderText="Name"></asp:BoundColumn>
<asp:ButtonColumn CommandName="Delete" HeaderText="Delete From List" Text="[Remove]"></asp:ButtonColumn>
</Columns>
</asp:DataGrid>
</div>
C# Code
protected void datagridTest_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowIndex == datagridTest.Items.Count - 1)
{
DropDownList ddl = new DropDownList();
e.Row.Cells[0].Controls.Add(ddl);
}
}
protected void datagridTest_ItemCommand(object source, DataGridCommandEventArgs e)
{
LinkButton lnkbtn = ((LinkButton)e.CommandSource);
if (e.CommandName == "Delete")
{
DataGridItem deletecontrol = (DataGridItem)lnkbtn.NamingContainer;
string bomb = deletecontrol.Cells[0].Text;
RemoveFireflyFromList(bomb);
RefreshdatagridTest();
}
}
How the grid gets data bound
protected void listselect_SelectedIndexChanged(object sender, EventArgs e)
{
RefreshdatagridTest();
}
private void RefreshdatagridTest()
{
dataSet = Run sql procedure to get results;
this.datagridTest.DataSource = dataSet;
this.datagridTest.DataBind();
}
its bit differente since in my exemple i generate new row at runtime but basicaly its how it work;
in my case had to add some size param or control was hidden.
so i just get to set control row's and add the row to the grid.
Mycontrol m = new Mycontrol();
RowDefinition rowDef1 = new RowDefinition();
rowDef1.MaxHeight = m.ExpandedSise;
rowDef1.MinHeight = m.Height;
rowDef1.Height = new GridLength(m.RowDefColapsedSize);
int rownumber = grid2.RowDefinitions.Count;
grid2.RowDefinitions.Insert(rownumber, rowDef1);
Grid.SetRow(m, rownumber);
m.counter.Content = Grid.GetRow(m).ToString();
grid2.Children.Add(m);

GridView and DetailsView Code Behind to Update DetailsView

I've spent all afternoon trying to do this using CODE BEHIND without success so I am asking for some C# code.
Basically, I have a GV and a DV in a master/detail relationship. GV displays ID and Name. If I click Select on a GV row, I want to see its ID, Name and Address in DV. I know how get this to work declaratively in an aspx file. But in C# code behind, I don't know how to proceed at this function:
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName.Equals("Select"))
{
// PLEASE GIVE ME THE CODE HERE TO BIND THE DETAILSVIEW. THANKS!
// I am using a sqldatasource if it makes any difference
}
}
Here's a general solution showing you how to achieve this, please note that this solution isn't extremely error-safe but I suppose you'll get the jist of it. Please comment if there's anything unclear.
Code-behind:
protected void gv_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "Select")
{
GridViewRow selected = gv.Rows[Convert.ToInt32(e.CommandArgument)];
List<ThatClass> cList = new List<ThatClass>();
cList.Add(new ThatClass(selected.Cells[0].Text, selected.Cells[1].Text));
dv.DataSource = cList;
dv.DataBind();
}
}
Markup:
<asp:GridView ID="gv" runat="server" AutoGenerateColumns="false" OnRowCommand="gv_RowCommand">
<Columns>
<asp:BoundField DataField="A" HeaderText="A"/>
<asp:BoundField DataField="B" HeaderText="B" />
<asp:CommandField ShowSelectButton="true" />
</Columns>
</asp:GridView>
<asp:DetailsView runat="server" ID="dv">
</asp:DetailsView>
FYI: I bound the GV using a List:
protected void Page_Load(object sender, EventArgs e)
{
List<ThatClass> cList = new List<ThatClass>();
cList.Add(new ThatClass("123", "abc"));
cList.Add(new ThatClass("456", "def"));
gv.DataSource = cList;
gv.DataBind();
}

All GridView rows disappear while selecting a row

Please consider the values in comments which I got in debug mode:
protected void FilesGrid_SelectedIndexChanged(object sender, EventArgs e)
{
int selected = FilesGrid.SelectedIndex; // selected = 2
FilesGrid.DataBind(); //added after feedback in comments. it makes no change
int count = FilesGrid.Rows.Count; // count = 0
GridViewRow row = FilesGrid.Rows[selected]; // row = null
GridViewRow row0 = FilesGrid.Rows[0]; // row = null
}
I came to this code while investigating why SelectedValue gives null in this event handler (the DataKeyNames parameter was set for sure).
Can anybody explain how it is possible?
Thank you in advance.
PS.
Here is my aspx code:
<asp:GridView ID="FilesGrid" runat="server" AutoGenerateColumns="False"
AutoGenerateSelectButton="True"
onselectedindexchanged="FilesGrid_SelectedIndexChanged"
style="margin-top: 0px" >
<Columns>
<asp:CommandField ShowDeleteButton="True" />
<asp:BoundField DataField="Name" HeaderText="Name" />
<asp:BoundField DataField="Length" DataFormatString="{0:N0}"
HeaderText="Size in Bytes" HtmlEncode="False" />
</Columns>
</asp:GridView>
Here is how I bind data:
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
string [] dd = {"FullName"};
FilesGrid.DataKeyNames = dd;
string appPath = Request.PhysicalApplicationPath;
DirectoryInfo dirInfo = new DirectoryInfo(appPath);
FileInfo[] files = dirInfo.GetFiles();
FilesGrid.DataSource = files;
FilesGrid.DataBind(); }
}
Y copy pasted your code, delete this line FilesGrid.DataBind() in the FilesGrid_SelectedIndexChanged, i see that are 2 methods that you are not posting, that aren't in the code that you posted the onselectedindexchanging, onrowdeleting events, comment them from the aspx and see if it works, or se if that events are not doing something tricking, that are deleting the rows in your GridView.
Tell me if it works
I did this
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
string[] dd = { "FullName" };
FilesGrid.DataKeyNames = dd;
string appPath = Request.PhysicalApplicationPath;
DirectoryInfo dirInfo = new DirectoryInfo(appPath);
FileInfo[] files = dirInfo.GetFiles();
FilesGrid.DataSource = files;
FilesGrid.DataBind();
}
}
protected void FilesGrid_SelectedIndexChanged(object sender, EventArgs e)
{
int selected = FilesGrid.SelectedIndex; // selected = 2
//FilesGrid.DataBind(); //added after feedback in comments. it makes no change
int count = FilesGrid.Rows.Count; // count = 0
GridViewRow row = FilesGrid.Rows[selected]; // row = null
GridViewRow row0 = FilesGrid.Rows[0]; // row = null
}
protected void FilesGrid_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
}
protected void FilesGrid_SelectedIndexChanging(object sender, GridViewSelectEventArgs e)
{
}
The aspx code.
<asp:ScriptManager ID="ScriptManager1" runat="server" EnableScriptGlobalization="true"
AsyncPostBackTimeout="0" EnableScriptLocalization="true">
</asp:ScriptManager>
<asp:UpdatePanel ID="upPanel" runat="server">
<ContentTemplate>
<asp:GridView ID="FilesGrid" runat="server" AutoGenerateColumns="False" AutoGenerateSelectButton="True"
OnRowDeleting="FilesGrid_RowDeleting" OnSelectedIndexChanged="FilesGrid_SelectedIndexChanged"
Style="margin-top: 0px" OnSelectedIndexChanging="FilesGrid_SelectedIndexChanging">
<Columns>
<asp:CommandField ShowDeleteButton="True" />
<asp:BoundField DataField="Name" HeaderText="Name" />
<asp:BoundField DataField="Length" DataFormatString="{0:N0}" HeaderText="Size in Bytes"
HtmlEncode="False" />
</Columns>
</asp:GridView>
</ContentTemplate>
</asp:UpdatePanel>
remove the FilesGrid.DataBind(); //added after feedback in comments. it makes no change
When I add that statement to my code I am getting the error. after removing that please try again. If not working please share the
protected void FilesGrid_SelectedIndexChanging(object sender, GridViewSelectEventArgs e) method code, may be something wrong with that section
The issue was resolved by commenting out the line // if (!Page.IsPostBack). It looks like the data source is lost somehow during the postback. The whole seems to be a local bug with ViewState, because this behavior was not observed by other users. My special thanks to Tim Schmelter and naveen.
You can keep Page.IsPostBack in Page_Load, I was having the same issue and it turns out the grid was not in ViewState in my case. If you use Linq query in your controller you will want to add this property to the grid so it will keep refreshing properly:
<asp:Panel EnableViewState="True">

Categories