how to get boundfield value of a gridview in rowupdating event - c#

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

Related

Edit GridView using BoundField Column in ASP.Net

I am using GridView for Showing Some Data with Editable Format. But When I am Editing the GridView row I don't get the Value of editable Textbox. Again I get the old Value.Please any one give some Suggestion.
Thanks in Advance...
Aspx Code:
<asp:GridView ID="grdAppSetting" AutoGenerateEditButton="true" AutoGenerateDeleteButton="true" HeaderStyle-BackColor="#1abc9c" HeaderStyle-ForeColor="White" CssClass="t-transform m-t-30" HeaderStyle-BorderWidth="5px"
runat="server" OnRowCancelingEdit="grdAppSetting_RowCancelingEdit1" OnRowDeleting="grdAppSetting_RowDeleting" OnRowUpdating="grdAppSetting_RowUpdating"
OnRowEditing="grdAppSetting_RowEditing" AutoGenerateColumns="false" BorderColor="#1abc9c">
<Columns>
<asp:BoundField DataField="Key Name" HeaderText="Key Name" ReadOnly="true" ItemStyle-CssClass="p-l-10" ItemStyle-Width="100" />
<asp:BoundField DataField="Value" HeaderText="Value" ItemStyle-Height="40px" ItemStyle-Width="50%" ItemStyle-CssClass="p-l-10" ControlStyle-CssClass="form-control" />
</Columns>
</asp:GridView>
C# Code:
protected void grdAppSetting_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
string Value = ((grdAppSetting.Rows[e.RowIndex].Cells[2].Controls[0]) as TextBox).Text;
string KeyName = grdAppSetting.Rows[e.RowIndex].Cells[1].Text;
if (appSettingsSection != null)
{
appSettingsSection.Settings[KeyName].Value = Value;
configuration.Save();
}
grdAppSetting.EditIndex = -1;
BindAppSettingGrid();
}
Problem occurred in the following line,
string Value = ((grdAppSetting.Rows[e.RowIndex].Cells[2].Controls[0]) as TextBox).Text;
Is this is correct to get the editable textbox value???

C# asp.net Gridview navigate to url in gridview row

I'm currently working on an in house project, I've created a GridView connected to a SQL table which looks like this:
GridView1
I created the view content buttons using the following code:
<Columns>
<asp:ButtonField ButtonType="Button" Text="View Content" CommandName="Select" />
<asp:BoundField DataField="ContentID" HeaderText="ContentID" InsertVisible="False" ReadOnly="True" SortExpression="ContentID" />
<asp:BoundField DataField="Code" HeaderText="Code" SortExpression="Code" />
<asp:BoundField DataField="Name" HeaderText="Name" SortExpression="Name" />
<asp:BoundField DataField="Description" HeaderText="Description" SortExpression="Description" />
<asp:BoundField DataField="URL" HeaderText="URL" Visible="true" SortExpression="URL" />
</Columns>
But this is where I am now stuck. I would like to click on the view content button and have it navigate to the URL on the selected row.
The URL comes from the SQL Table and there is a string so I'd imagine, it would need to be converted first but I could be wrong.
I started to put my code in the following:
protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
{
GridViewCommandEventArgs x = (GridViewCommandEventArgs)e;
if (x.CommandName == "Select")
{
GridViewRow row = GridView1.SelectedRow;
}
}
Add your code in GridView1_RowCommand event of gridview:
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "Select")
{
GridViewRow row = (GridViewRow)(((BoundField)e.CommandSource).NamingContainer);
int index = row.RowIndex;
string url = (GridView1.Rows[index].FindControl("URL") as BoundField).Text;
Response.Redirect(url); // url can be from your sql table
}
}
Note: Don't forget to add OnRowCommand event in GrindView <asp:GridView ID="GridView1" runat="server" OnRowCommand="GridView1_RowCommand" >
GridViewRow row = (GridViewRow)(((BoundField)e.CommandSource).NamingContainer);
int index = row.RowIndex;
string url = (GridView1.Rows[index].FindControl("URL") as BoundField).Text;
Response.Redirect(url); // url can be from your sql table
So i made the change. Unfortunately, BoundField does not contain a definition for NamingContainer.
Also, GridView1.Rows[index].FindControl("URL") as BoundField fails due to the following error, cannot convert type 'system.web.ui.control' to 'system.web.ui.webcontrols.boundfield' via a reference conversion, boxing conversion, unboxing conversion or null type conversion.

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.

unable to update gridview values in .net

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.
}
}

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