Confirm delete before deleting dataview's row - asp.net

I have a GridView which supports deleting. I'd like to add a pop up window with a question like 'Are you sure you want to delete this row?'.
My code:
<asp:GridView id="GridAccounts" runat="server" AutoGenerateColumns="False"
ShowFooter="True" DataKeyNames="ID"
DataSourceID="AccountDataSource" onrowcommand="GridAccounts_RowCommand">
<SelectedRowStyle BackColor="Lime" />
<Columns>
<asp:CommandField ButtonType="Image" ShowDeleteButton="True" DeleteImageUrl="~/Pictures/delete.jpg" />
<asp:TemplateField HeaderText="ID" InsertVisible="False" SortExpression="ID">
<EditItemTemplate>
<asp:Label ID="LabelAccountIDUpdate" runat="server" Text='<%# Eval("ID") %>'></asp:Label>
</EditItemTemplate>
<FooterTemplate>
<asp:Button ID="ButtonAccountIDInsert" runat="server" CommandName="Insert" Text="Insert" />
</FooterTemplate>
<ItemTemplate>
<asp:Label ID="LabelAccountID" runat="server" Text='<%# Bind("ID") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Code behind:
protected void GridPaymentMethod_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
ImageButton deleteButton = (ImageButton)e.Row.Cells[0].Controls[0];
MyMoney.PaymentMethodRow row = (MyMoney.PaymentMethodRow)((System.Data.DataRowView)e.Row.DataItem).Row;
deleteButton.OnClientClick = string.Format("return confirm('Are you sure you want to delete payment method {0}?');", row.Name.Replace("'", #"\'"));
}
}
This renders as:
<input type="image" src="Pictures/delete.jpg" alt="Delete" onclick="return confirm('Are you sure you want to delete payment method Gotovina?');javascript:__doPostBack('ctl00$MainContent$GridPaymentMethod','Delete$0')" style="border-width:0px;" />
If I click OK on confirmation window, postback occurs, but nothing happens. If I comment out RowDataBound code, than delete works OK. Code whithout confirmation pop up:
<input type="image" src="Pictures/delete.jpg" alt="Delete" onclick="javascript:__doPostBack('ctl00$MainContent$GridPaymentMethod','Delete$0')" style="border-width:0px;" />
What am I doing wrong?

I believe this is an example of what you are trying to do. It's cleaner and you don't have to go nutz with the code behind.

In your code you must change ButtonType="Image" to ButtonType="Link" - then onclick="..." will be rendered without javascript:___doPostBack(...) part. And in the GridPaymentMethod_RowDataBound event set something like deleteButton.Text = "<img src=\"path_to_image\" ... />" (use html entities instead of <>).
Or you can use ImageButton with ComamndName="delete" and ConfirmButtonExtender from ASP.NET AjaxToolkit suite.

deleteButton.OnClientClick = string.Format("((!confirm('Are you sure you want to delete payment method {0}?'))?return false);", row.Name.Replace("'", #"\'"));

Related

Gridview Delete Linkbutton not firing RowDeleting Event

I am so frustrated. Using asp.net GridView. Using a LinkButton with the CommandName="Delete". Don't understand why the page isn't posting back. I've done this a million times in other apps. I've compared them against one another and nothing appears different. I will preface by saying this IS someone else's template, however, so it's not my same template.
Any ideas what might be causing my issues?
My scenario is this:
ASPX Page (edited to add the HTML; there's more HTML in the site.Master and there's also a tag for the AjaxControlToolkit at the top of the page):
<div class="width80 container body-content">
<h2 class="marginTop50">Message Board</h2>
<asp:Panel ID="pnlMsgsForUser" runat="server" Visible="false">
<div class="jumbotronSmallFont">
<asp:Label ID="lblErrorMessage" CssClass="has-error" runat="server"></asp:Label>
</div>
</asp:Panel>
<div class="jumbotronSmallFont">
<h4>New Message</h4>
<form>
<div class="form-group">
<label for="messageBody">Message Body</label>
<textarea class="form-control" id="messageBody" rows="3" style="max-width: 600px;"></textarea>
</div>
<div class="text-center">
<button id="btnSave" class="btn btn-primary" style="width: 75px;">Save</button>
<button type="button" id="btnReset" class="btn btn-default marginLeft15px" style="width: 75px;">Reset</button>
</div>
</form>
</div>
<div>
<asp:GridView ID="gvMessages" runat="server" Width="100%"
CssClass="table adminMessageBoardTable marginAuto" AutoGenerateColumns="False"
OnRowUpdating="gvMessages_RowUpdating"
OnRowCancelingEdit="gvMessages_RowCancelingEdit"
OnRowDataBound="gvMessages_RowDataBound"
OnRowEditing="gvMessages_RowEditing"
OnRowDeleting="gvMessages_RowDeleting"
DataKeyNames="Id" BorderStyle="NotSet">
<Columns>
<asp:TemplateField HeaderText="Message" HeaderStyle-CssClass="center" SortExpression="Message">
<EditItemTemplate>
<asp:TextBox ID="txtMsg" Width="100%" runat="server"></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label runat="server" Text='<%# Eval("MessageBody") %>' ID="lblMessage"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Date Updated" SortExpression="DateUpdated" HeaderStyle-CssClass="center" ItemStyle-CssClass="center">
<HeaderStyle Width="120px" />
<EditItemTemplate>
<asp:Label runat="server" ID="lblEditDateUpdated" Enabled="false"></asp:Label>
</EditItemTemplate>
<ItemTemplate>
<asp:Label runat="server" Text='<%# Eval("DateUpdated","{0:d}") %>' ID="lblDateUpdated"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Updated By" SortExpression="UpdatedBy" HeaderStyle-CssClass="center" ItemStyle-CssClass="center">
<HeaderStyle Width="120px" />
<EditItemTemplate>
<asp:Label runat="server" Text="" ID="lblEditUpdatedBy" Enabled="false"></asp:Label>
</EditItemTemplate>
<ItemTemplate>
<asp:Label runat="server" Text='<%# Eval("UpdatedBy") %>' ID="lblUpdatedBy"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField ItemStyle-CssClass="center">
<HeaderStyle Width="120px" />
<EditItemTemplate>
<asp:LinkButton ID="lbUpdate" runat="server" CausesValidation="True"
CommandName="Update" Text="Update"
OnClientClick="return confirm('You are about to update this entry. \n\nDo you wish to proceed?');"></asp:LinkButton>
<asp:LinkButton ID="lbCancel" runat="server" CausesValidation="False"
CommandName="Cancel" Text="Cancel"></asp:LinkButton>
</EditItemTemplate>
<ItemTemplate>
<asp:LinkButton ID="lbEdit" runat="server" CausesValidation="False"
CommandName="Edit" Text="Edit"></asp:LinkButton>
<asp:LinkButton ID="lbDelete" runat="server" CommandArgument='<%# Eval("Id") %>' CausesValidation="False"
CommandName="Delete" Text="Delete" OnClientClick="return confirm('You are about to delete this entry. \n\Do you wish to proceed?');"></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</div>
</div>
In my code-behind, I have:
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
var user = CommonFunctions.GetUserID(true);
var Admin = Roles.IsUserInRole(user, "Administrator");
var Dev = Roles.IsUserInRole(user, "Developer");
if (!Admin && !Dev)
{
Response.Redirect("~/");
}
gvBind(true);
}
}
When I click on the Delete linkbutton for a row, it drops into the Page_Load and
!Page.IsPostBack
verifies as true. I have no idea why it's doing this. It also never even hits the RowDeleting command. My breakpoint is so sad.
In my other app, all the markup and code-behind are pretty much the same. The only differences are the gridview name and the Eval tags. But when I click Delete in that app, it skips the !Page.IsPostBack section. :( It also obviously fires the RowDeleting.
I've also tried implementing RowCommand, but that event never fires either. It only does Page_Load and RowDataBound before essentially refreshing the page.
Any ideas?
Please, and thanks!!!
Your code is working fine. When I click Delete button, it triggers gvMessages_RowDeleting event. Here is how I test it -
<asp:GridView ID="gvMessages" runat="server" Width="100%"
CssClass="GridView marginAuto" AutoGenerateColumns="False"
OnRowDeleting="gvMessages_RowDeleting"
DataKeyNames="Id">
<Columns>
<asp:TemplateField HeaderText="Message" HeaderStyle-CssClass="center" SortExpression="Message">
<ItemTemplate>
<asp:Label runat="server" Text='<%# Eval("MessageBody") %>' ID="lblMessage"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField ItemStyle-CssClass="center">
<ItemTemplate>
<asp:LinkButton ID="lbDelete" runat="server" CommandArgument='<%# Eval("Id") %>' CausesValidation="False"
CommandName="Delete" Text="Delete"
OnClientClick="confirm('You are about to delete this entry. \n\Do you wish to proceed?');"></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Code Behind
public class Item
{
public int Id { get; set; }
public string MessageBody { get; set; }
}
public partial class _Default : Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
gvMessages.DataSource = new List<Item>
{
new Item {Id = 1, MessageBody = "One"},
new Item {Id = 2, MessageBody = "Two"},
new Item {Id = 3, MessageBody = "Three"},
};
gvMessages.DataBind();
}
}
protected void gvMessages_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
}
}
OnClientClick="return confirm('Are you sure?');"
Try to add the return from your confirm statement.

Model binding to formview when Gridview Edit button is clicked

I have searched here and on google as well.Things are not working so I'm posting this.
I have two controls GridView and FormView.I am using Model binding in my project.
<asp:GridView ID="GridView1" runat="server" DataKeyNames="Id" ItemType="Sample.Shared.ViewModel.ProfileMasterView"
AutoGenerateColumns="false" SelectMethod="Select_GridView">
<Columns>
<asp:BoundField DataField="Name" HeaderText="Name" />
<asp:BoundField DataField="Designation" HeaderText="Designation" />
<asp:BoundField DataField="EmailAddress" HeaderText="EmailAddress" />
<asp:TemplateField HeaderText="Action">
<ItemTemplate>
<asp:Button ID="Edit_Profile" OnClick="btnEdit_OnClick" runat="server" Text="Edit" CommandArgument="<%# BindItem.Id %>" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<asp:FormView ID="fvProfile" runat="server" RenderOuterTable="False" ItemType="Sample.Shared.ViewModel.ProfileMasterView"
DefaultMode="Insert" InsertMethod="Insert_Profile" >
I want to open FormView in Edit mode , where in gridview i am sending id of that record.On button click i want to change formview mode by calling BLL method which takes that Id from button click and retrieved record displayed in form view in edit mode.
Please help me , how can i implement this or any other similar way using model binding only,
Thank you.
As no one seems to answer this.I have found work around and also proper method for doing,I will add the answer as i get time from work.
before
asp:Button ID="Edit_Profile" OnClick="btnEdit_OnClick" runat="server" Text="Edit" CommandArgument="<%# BindItem.Id %>"
asp:FormView ID="fvProfile" runat="server" RenderOuterTable="False" ItemType="Sample.Shared.ViewModel.ProfileMasterView"
DefaultMode="Insert" InsertMethod="Insert_Profile"
after
asp:Button ID="Edit_Profile" OnCommand="btnEdit_OnClick" runat="server" Text="Edit" CommandArgument="<%# BindItem.Id %>"
asp:FormView ID="fvProfile" runat="server" RenderOuterTable="False" ItemType="Sample.Shared.ViewModel.ProfileMasterView" SelectMethod="Get"
DefaultMode="Insert" InsertMethod="Insert_Profile"
protected void btnEdit_OnClick(object sender, CommandEventArgs e)
{
gId = Convert.ToInt32(e.CommandArgument.ToString());
fvProfile.ChangeMode(FormViewMode.Edit);
fvProfile.Visible = true;
GridView1.Visible = false;
fvProfile.DataBind();
}
public DAL2.Models.OfficialDocument Get()
{
if(gId == 0)
{
ChangeViewMode();
return null;
}
BLL.ManageOfficialDocument mod = new BLL.ManageOfficialDocument();
var od = mod.GetById(gFILES_ID);
return od;
}
private int gId;

Using asp:Button with OnRowDeleting event

I'm trying to connect an asp:Button with my OnRowDeleting event in a gridview, but I don't don't know how to do that :X. I'm currently using CommandField but for my own purposes I need it with a Button instead. Can anyone help me please?
EDIT:
Let me re-explain, I have a row with Delete and Edit buttons in the same CommandField. What I'm trying to do is to hide the 'Delete' button in some specific cases for specific rows only and not necessarily for every row. That's why I'm struggling with a CommandField because there's no ID coming with it so I can't refer to it in my codebehind. But - asp:Button has an ID but I can't manage to link it with the UserAccounts_RowDeleting function. And that's my question - how to link it? :)
EDIT2:
These are part of my codes:
<asp:GridView ID="UserAccounts" runat="server" AutoGenerateColumns="False" HeaderStyle-BackColor="#3AC0F2"
HeaderStyle-ForeColor="White" AutoGenerateDeleteButton="false"
RowStyle-BackColor="#A1DCF2" AlternatingRowStyle-BackColor="White" AutoGenerateEditButton="false"
onrowcancelingedit="UserAccounts_RowCancelingEdit" RowStyle-ForeColor="#3A3A3A" OnRowEditing="UserAccounts_RowEditing"
PageSize="10" AllowPaging="false" onrowdeleting="UserAccounts_RowDeleting"
OnRowUpdating="UserAccounts_RowUpdating" OnRowDataBound="UserAccounts_RowDataBound" onrowcreated="UserAccounts_RowCreated">
<Columns>
<asp:CommandField ShowDeleteButton="true" ShowEditButton='true' ButtonType="Link" />
<asp:BoundField DataField="UserName" HeaderText="Username" ReadOnly="true"/>
<asp:BoundField DataField="Email" HeaderText="Email" />
<asp:CheckBoxField DataField="IsApproved" HeaderText="Approved?" ReadOnly="false"/>
<asp:CheckBoxField DataField="IsLockedOut" HeaderText="Locked Out?" ReadOnly="true"/>
<asp:CheckBoxField DataField="IsOnline" HeaderText="Online?" ReadOnly="true"/>
<asp:BoundField DataField="Comment" HeaderText="Comment" NullDisplayText="N/A"/>
<asp:TemplateField HeaderText="Select" >
<ItemTemplate>
<asp:CheckBox ID="CheckBox1" runat="server" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
//Codebehind c#
protected void UserAccounts_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
if (Funcs.GetAdminLevel() >= 999)
{
username = UserAccounts.Rows[e.RowIndex].Cells[1].Text;
if (username.ToLower().Equals(HttpContext.Current.User.Identity.Name.ToLower()))
ActionStatus.Text = string.Format("ERROR: You can't delete your own account ('<font color=#000000><b>{0}</b></font>')!", username);
else if (Funcs.GetAdminLevel(username) >= 1)
ActionStatus.Text = string.Format("ERROR: You can't delete administrators' accounts ('<font color=#000000><b>{0}</b></font>')!", username);
else
{
Roles.RemoveUserFromRoles(username, Roles.GetRolesForUser(username));
Membership.DeleteUser(username);
ActionStatus.Text = string.Format("User '<font color=#000000><b>{0}</b></font>' has been successfully deleted!", username);
BindUserAccounts();
}
}
else
ActionStatus.Text = "You are not authorized to delete user accounts!";
}
I want to change the CommandField to ItemTemplate so I can enable/disable it through the codebehind for specific rows only. Also, I want the ItemTemplate, which would be asp:Button, to use the UserAccounts_RowDeleting event and that's where my problem is, I just don't know how to link the button to the event..
It sounds like you pretty much have the solution already. Use a TemplateField for your button. The key part is to set the CommandName of your button to "Delete". This tells the GridView that it is a delete button and the RowDeleting event should handle it.
<asp:TemplateField>
<ItemTemplate>
<asp:Button ID="btnDelete" runat="server" Text="Delete" CommandName="Delete" />
</ItemTemplate>
</asp:TemplateField>

Call a clientsideevent from another clientsideevent

ASP.net(C#), VS2010, Win 7.
New to WebDev, so this might be a simple syntax thing but here it goes...
Long story short I have to force a postback on a GridView that shows attachments I upload using an ASPxUploadControl. I put the GridView inside an ASPxCallbackPanel and am trying to get my GridView to update on the page after an attachment is uploaded using ASPxCallbackPanel.PerformCallback();
Here's the Upload control, in its' ClientSideEvent is where I'm trying to call the clientSideEvent from the Button shown below. Just trying to force a button click really, but I tried doing it from the code-behind but that didn't work. Any help would be appreciated!
<dxuc:ASPxUploadControl ID="FileUpload1" runat="server"
ClientInstanceName="uploader"
ShowAddRemoveButtons="False"
ShowUploadButton="True"
AddUploadButtonsHorizontalPosition="Center"
AddUploadButtonsVerticalPosition="Top" FileInputCount="1"
UploadMode="Advanced"
OnFileUploadComplete="UploadControl_FileUploadComplete"
Size="30">
<ClientSideEvents FileUploadComplete="function(s, e) { Button1.Click; }" />
<%-- <AdvancedModeSettings EnableMultiSelect="True" /> "does not have public property named "advancedModeSettings" version is too old--%>
<ValidationSettings
AllowedFileExtensions=".doc,.pdf,.xls,.txt,.jpeg,.jpg,.gif,.png,.oft,.htm,.html,.mht,.rtf,.zip"
MaxFileSize="5242880"
FileDoesNotExistErrorText="This file can't be found."
GeneralErrorText="Custom file uploading fails due to an external error that doesn't relate to the ASPxUploadControl's functionality"
MaxFileSizeErrorText="Size of the uploaded file exceeds maximum file size">
<ErrorStyle ForeColor="Red"/>
</ValidationSettings>
</dxuc:ASPxUploadControl>
Here is the GridView as well as a button I made that successfully refreshes the grid.
<div>
<dxe:ASPxButton ID="ASPxButton1" runat="server" ClientInstanceName="Button1" Text="Reload Panel" AutoPostBack="False">
<ClientSideEvents Click="function(s, e) {ASPxCallbackPanel1.PerformCallback(); e.processOnServer = true;}" />
</dxe:ASPxButton>
<dx:ASPxCallbackPanel ID="ASPxCallbackPanel1" runat="server"
ClientInstanceName="ASPxCallbackPanel1" Width="492px"
Height="100%">
<PanelCollection>
<dx:PanelContent runat="server">
<asp:GridView ID="gvAttachment" SkinID="grid" runat="server" Width="98%"
OnRowDataBound="AttachmentControl_OnRowDataBound"
meta:resourcekey="gvAttachResource1"
PagerSettings-FirstPageText="<%$ Resources:CommonControlText,FirstPageText %>"
PagerSettings-LastPageText="<%$ Resources:CommonControlText,LastPageText %>"
PagerSettings-PreviousPageText="<%$ Resources:CommonControlText,PreviousPageText %>"
PagerSettings-NextPageText="<%$ Resources:CommonControlText,NextPageText %>"
AutoGenerateColumns="False">
<EmptyDataRowStyle CssClass="emptyData" />
<EmptyDataTemplate>
<table class="usercontroldetail container_table">
<tr>
<td class="tdlayout">
<asp:Label ID="Localize1" runat="server">
<%= Placeholder %>
</asp:Label>
</td>
</tr>
</table>
</EmptyDataTemplate>
<Columns>
<asp:BoundField DataField="AtchmtId" HeaderText="Attachment ID"
visible = "false" meta:resourcekey="BoundFieldResource1">
<ItemStyle HorizontalAlign="Center" />
</asp:BoundField>
<asp:BoundField DataField ="FileNm" HeaderText="File Name" />
<asp:BoundField DataField="UsrNm" HeaderText="Uploaded By"
/>
<asp:BoundField DataField="AtchmtDt" HeaderText="Date"
/>
<asp:BoundField DataField="FileSizeCnt" HeaderText="File Size"
/>
<asp:TemplateField AccessibleHeaderText="Actions" HeaderText="Actions">
<ItemTemplate>
<div style="text-align:center;">
<asp:LinkButton ID="btnDelete" Visible="False" runat="server"
ToolTip="Delete Selected Attachment"
OnClick="btnDelete_Click"
Text="Delete" CausesValidation="True" DisableOnSubmit="True" Group=""
meta:resourcekey="btnDeleteResource1" />
<asp:Label ID="lblPipe" runat="server" Text="|" />
<asp:LinkButton ID="btnView" Visible="False" runat="server"
ToolTip="View Selected Attachment"
OnClick="btnView_Click"
Text="View" CausesValidation="True" DisableOnSubmit="True" Group=""
meta:resourcekey="btnViewResource1" />
</div>
</ItemTemplate>
<ItemStyle Wrap="false" />
</asp:TemplateField>
</Columns>
<%--<PagerSettings FirstPageText="First" LastPageText="Last" NextPageText="Next >" PreviousPageText="< Previous"></PagerSettings>--%>
<RowStyle CssClass="row_odd" />
<AlternatingRowStyle CssClass="row_even" />
</asp:GridView>
</dx:PanelContent>
</PanelCollection>
</dx:ASPxCallbackPanel>
FYI: The GridView is getting the new attachment put in it. I'm just not seeing it on the page because the UploadControl only updates itself.
Edit:Figured it out just used the OnClick() method as below. Derp. Forgot that the ASPx button inherited all the ASP buttons methods. But now my original plan of making the button invisible seems to be foiled. When Button1.OnClick() is called with the Visible property for the Button set to "false". it says Button1 is not defined. Anyway around this?
<ClientSideEvents FileUploadComplete="function(s, e) { Button1.OnClick(); }" />
If I got you right, you can manipulate the behavior of all update panels on page via property called a updateMode (Conditional, Always). Changing one updatepanel will cause refreshing of all, if all have mode set to Always.

Gridview row editing - dynamic binding to a DropDownList

I'm trying to get an ASP.NET 3.5 GridView to show a selected value as string when being displayed, and to show a DropDownList to allow me to pick a value from a given list of options when being edited. Seems simple enough?
My gridview looks like this (simplified):
<asp:GridView ID="grvSecondaryLocations" runat="server"
DataKeyNames="ID" OnInit="grvSecondaryLocations_Init"
OnRowCommand="grvSecondaryLocations_RowCommand"
OnRowCancelingEdit="grvSecondaryLocations_RowCancelingEdit"
OnRowDeleting="grvSecondaryLocations_RowDeleting"
OnRowEditing="grvSecondaryLocations_RowEditing"
OnRowUpdating="grvSecondaryLocations_RowUpdating" >
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:Label ID="lblPbxTypeCaption" runat="server"
Text='<%# Eval("PBXTypeCaptionValue") %>' />
</ItemTemplate>
<EditItemTemplate>
<asp:DropDownList ID="ddlPBXTypeNS" runat="server"
Width="200px"
DataTextField="CaptionValue"
DataValueField="OID" />
</EditItemTemplate>
</asp:TemplateField>
</asp:GridView>
The grid gets displayed OK when not in editing mode - the selected PBX type shows its value in the asp:Label control. No surprise there.
I load the list of values for the DropDownList into a local member called _pbxTypes in the OnLoad event of the form. I verified this - it works, the values are there.
Now my challenge is: when the grid goes into editing mode for a particular row, I need to bind the list of PBX's stored in _pbxTypes.
Simple enough, I thought - just grab the drop down list object in the RowEditing event and attach the list:
protected void grvSecondaryLocations_RowEditing(object sender, GridViewEditEventArgs e)
{
grvSecondaryLocations.EditIndex = e.NewEditIndex;
GridViewRow editingRow = grvSecondaryLocations.Rows[e.NewEditIndex];
DropDownList ddlPbx = (editingRow.FindControl("ddlPBXTypeNS") as DropDownList);
if (ddlPbx != null)
{
ddlPbx.DataSource = _pbxTypes;
ddlPbx.DataBind();
}
.... (more stuff)
}
Trouble is - I never get anything back from the FindControl call - seems like the ddlPBXTypeNS doesn't exist (or can't be found).
What am I missing?? Must be something really stupid.... but so far, all my Googling, reading up on GridView controls, and asking buddies hasn't helped.
Who can spot the missing link? ;-)
Quite easy... You're doing it wrong, because by that event the control is not there:
protected void gv_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow &&
(e.Row.RowState & DataControlRowState.Edit) == DataControlRowState.Edit)
{
// Here you will get the Control you need like:
DropDownList dl = (DropDownList)e.Row.FindControl("ddlPBXTypeNS");
}
}
That is, it will only be valid for a DataRow (the actually row with data), and if it's in Edit mode... because you only edit one row at a time. The e.Row.FindControl("ddlPBXTypeNS") will only find the control that you want.
I am using a ListView instead of a GridView in 3.5. When the user wants to edit I have set the selected item of the dropdown to the exising value of that column for the record. I am able to access the dropdown in the ItemDataBound event. Here's the code:
protected void listViewABC_ItemDataBound(object sender, ListViewItemEventArgs e)
{
// This stmt is used to execute the code only in case of edit
if (((ListView)(sender)).EditIndex != -1 && ((ListViewDataItem)(e.Item)).DisplayIndex == ((ListView)(sender)).EditIndex)
{
((DropDownList)(e.Item.FindControl("ddlXType"))).SelectedValue = ((MyClass)((ListViewDataItem)e.Item).DataItem).XTypeId.ToString();
((DropDownList)(e.Item.FindControl("ddlIType"))).SelectedValue = ((MyClass)((ListViewDataItem)e.Item).DataItem).ITypeId.ToString();
}
}
protected void grvSecondaryLocations_RowEditing(object sender, GridViewEditEventArgs e)
{
grvSecondaryLocations.EditIndex = e.NewEditIndex;
DropDownList ddlPbx = (DropDownList)(grvSecondaryLocations.Rows[grvSecondaryLocations.EditIndex].FindControl("ddlPBXTypeNS"));
if (ddlPbx != null)
{
ddlPbx.DataSource = _pbxTypes;
ddlPbx.DataBind();
}
.... (more stuff)
}
You can use SelectedValue:
<EditItemTemplate>
<asp:DropDownList ID="ddlPBXTypeNS"
runat="server"
Width="200px"
DataSourceID="YDS"
DataTextField="CaptionValue"
DataValueField="OID"
SelectedValue='<%# Bind("YourForeignKey") %>' />
<asp:YourDataSource ID="YDS" ...../>
</EditItemTemplate>
The checked answer from balexandre works great. But, it will create a problem if adapted to some other situations.
I used it to change the value of two label controls - lblEditModifiedBy and lblEditModifiedOn - when I was editing a row, so that the correct ModifiedBy and ModifiedOn would be saved to the db on 'Update'.
When I clicked the 'Update' button, in the RowUpdating event it showed the new values I entered in the OldValues list. I needed the true "old values" as Original_ values when updating the database. (There's an ObjectDataSource attached to the GridView.)
The fix to this is using balexandre's code, but in a modified form in the gv_DataBound event:
protected void gv_DataBound(object sender, EventArgs e)
{
foreach (GridViewRow gvr in gv.Rows)
{
if (gvr.RowType == DataControlRowType.DataRow && (gvr.RowState & DataControlRowState.Edit) == DataControlRowState.Edit)
{
// Here you will get the Control you need like:
((Label)gvr.FindControl("lblEditModifiedBy")).Text = Page.User.Identity.Name;
((Label)gvr.FindControl("lblEditModifiedOn")).Text = DateTime.Now.ToString();
}
}
}
<asp:GridView ID="GridView1" runat="server" PageSize="2" AutoGenerateColumns="false"
AllowPaging="true" BackColor="White" BorderColor="#CC9966" BorderStyle="None"
BorderWidth="1px" CellPadding="4" OnRowEditing="GridView1_RowEditing" OnRowUpdating="GridView1_RowUpdating"
OnPageIndexChanging="GridView1_PageIndexChanging" OnRowCancelingEdit="GridView1_RowCancelingEdit"
OnRowDeleting="GridView1_RowDeleting">
<FooterStyle BackColor="#FFFFCC" ForeColor="#330099" />
<RowStyle BackColor="White" ForeColor="#330099" />
<SelectedRowStyle BackColor="#FFCC66" Font-Bold="True" ForeColor="#663399" />
<PagerStyle BackColor="#FFFFCC" ForeColor="#330099" HorizontalAlign="Center" />
<HeaderStyle BackColor="#990000" Font-Bold="True" ForeColor="#FFFFCC" />
<Columns>
<asp:TemplateField HeaderText="SerialNo">
<ItemTemplate>
<%# Container .DataItemIndex+1 %>.&nbsp
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="RollNo">
<ItemTemplate>
<%--<asp:Label ID="lblrollno" runat="server" Text='<%#Eval ("RollNo")%>'></asp:Label>--%>
<asp:TextBox ID="txtrollno" runat="server" Text='<%#Eval ("RollNo")%>'></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="SName">
<ItemTemplate>
<%--<asp:Label ID="lblsname" runat="server" Text='<%#Eval("SName")%>'></asp:Label>--%>
<asp:TextBox ID="txtsname" runat="server" Text='<%#Eval("SName")%>'> </asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="C">
<ItemTemplate>
<%-- <asp:Label ID="lblc" runat="server" Text='<%#Eval ("C") %>'></asp:Label>--%>
<asp:TextBox ID="txtc" runat="server" Text='<%#Eval ("C") %>'></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Cpp">
<ItemTemplate>
<%-- <asp:Label ID="lblcpp" runat="server" Text='<%#Eval ("Cpp")%>'></asp:Label>--%>
<asp:TextBox ID="txtcpp" runat="server" Text='<%#Eval ("Cpp")%>'> </asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Java">
<ItemTemplate>
<%-- <asp:Label ID="lbljava" runat="server" Text='<%#Eval ("Java")%>'> </asp:Label>--%>
<asp:TextBox ID="txtjava" runat="server" Text='<%#Eval ("Java")%>'> </asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Edit" ShowHeader="False">
<EditItemTemplate>
<asp:LinkButton ID="lnkbtnUpdate" runat="server" CausesValidation="true" Text="Update"
CommandName="Update"></asp:LinkButton>
<asp:LinkButton ID="lnkbtnCancel" runat="server" CausesValidation="false" Text="Cancel"
CommandName="Cancel"></asp:LinkButton>
</EditItemTemplate>
<ItemTemplate>
<asp:LinkButton ID="btnEdit" runat="server" CausesValidation="false" CommandName="Edit"
Text="Edit"></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
<asp:CommandField HeaderText="Delete" ShowDeleteButton="True" ShowHeader="True" />
<asp:CommandField HeaderText="Select" ShowSelectButton="True" ShowHeader="True" />
</Columns>
</asp:GridView>
<table>
<tr>
<td>
<asp:Label ID="lblrollno" runat="server" Text="RollNo"></asp:Label>
<asp:TextBox ID="txtrollno" runat="server"></asp:TextBox>
</td>
<td>
<asp:Label ID="lblsname" runat="server" Text="SName"></asp:Label>
<asp:TextBox ID="txtsname" runat="server"></asp:TextBox>
</td>
<td>
<asp:Label ID="lblc" runat="server" Text="C"></asp:Label>
<asp:TextBox ID="txtc" runat="server"></asp:TextBox>
</td>
<td>
<asp:Label ID="lblcpp" runat="server" Text="Cpp"></asp:Label>
<asp:TextBox ID="txtcpp" runat="server"></asp:TextBox>
</td>
<td>
<asp:Label ID="lbljava" runat="server" Text="Java"></asp:Label>
<asp:TextBox ID="txtjava" runat="server"></asp:TextBox>
</td>
</tr>
<tr>
<td>
<asp:Button ID="Submit" runat="server" Text="Submit" OnClick="Submit_Click" />
<asp:Button ID="Reset" runat="server" Text="Reset" OnClick="Reset_Click" />
</td>
</tr>
</table>

Resources