ASP.NET + GridView + EmptyDataTemplate - asp.net

I have an ASP.NET GridView that uses an EmptyDataTemplate. This template is used to collect data in the event that no records exist in my data source. My GridView source looks like this:
<asp:GridView ID="myGridView" runat="server"
DataKeyNames="ID" OnRowEditing="myGridView_RowEditing"
OnRowCancelingEdit="myGridView_RowCancelingEdit"
OnRowUpdating="myGridView_RowUpdating"
ShowFooter="True" EnableModelValidation="True">
<Columns>
<asp:BoundField DataField="ID" Visible="false" />
<asp:TemplateField HeaderText="Name">
<EditItemTemplate>
<asp:TextBox ID="TextBox1" runat="server" Text='<%# Bind("Name") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%# Bind("Name") %>'></asp:Label>
</ItemTemplate>
<FooterTemplate>
<asp:TextBox ID="nameFooterTextBox" runat="server" />
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Age">
<EditItemTemplate>
<asp:TextBox ID="TextBox2" runat="server" Text='<%# Bind("Age") %>' />
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label2" runat="server" Text='<%# Bind("Age") %>' />
</ItemTemplate>
<FooterTemplate>
<asp:TextBox ID="ageTextBox" runat="server" />
</FooterTemplate>
</asp:TemplateField>
<asp:CommandField HeaderText="Options" HeaderStyle-HorizontalAlign="Left"
ButtonType="Link" ShowEditButton="true" ShowDeleteButton="true" >
</asp:CommandField>
</Columns>
<EmptyDataTemplate>
<table border="0" cellpadding="0" cellspacing="0">
<tr>
<td>Name</td>
<td>Age</td>
<td>Options</td>
</tr>
<tr>
<td><asp:TextBox ID="nameTextBox" runat="server" /></td>
<td><asp:TextBox ID="ageTextBox" runat="server" /></td>
<td><asp:LinkButton ID="saveLinkButton" runat="server" Text="save" OnClick="saveLinkButton_Click" /></td>
</tr>
</table>
</EmptyDataTemplate>
When a user clicks the "saveLinkButton" in the EmptyDataTemplate, I want to get the values from the TextBoxes and insert a new record into my data source. My question is, how do I get the values of those text fields when somebody clicks the "saveLinkButton"?
Thank you!

This thread over at asp.net proposes a solution to this problem (Note: I haven't tried it out)
http://forums.asp.net/p/1436652/3240106.aspx
You need to handle the RowCommand event, get the parent naming container of the control that raise the event (your linkbutton) and then search for the textboxes using FindControl within that.

Try this to get the values of the name and age in row command of the grid..
Before doing this set the command name of the saveLinkbutton to MyInsert and remove the onlcik event as u may not need it.
protected void yourGridview_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName.Equals("MyInsert"))
{
TextBox nameTextBox= gvEligibility.Controls[0].Controls[0].FindControl("nameTextBox") as TextBox;
TextBox ageTextBox= gvEligibility.Controls[0].Controls[0].FindControl("ageTextBox") as TextBox;
string name=nameTextBox.Text();
string age=ageTextBox.Text();
//save code here
}
}

Related

Setting EditIndex on a asp:GridView, can I be sure it is the correct row after rebinding to live data has been done?

Having an asp:GridView, when I put it into edit mode by setting EditIndex, I also need to update its data using the DataSource property and call DataBind like this:
protected void GrdFoo_OnRowEditing(object sender, GridViewEditEventArgs e)
{
grdFoo.EditIndex = e.NewEditIndex;
grdFoo.DataSource = DataBase.GetFoos();
grdFoo.DataBind();
}
Now, if the database contents was changed since I was populating the gridview first, how can I be sure I will edit the correct row?
edit
I got the suggestion to use OnRowDataBound. I am using a command field to trigger GrdFoo_OnRowEditing. Is the use of OnRowDataBound still a good idea?
Here is how I use the CommandField (aspx):
<asp:GridView ID="grdFoo" runat="server"
OnRowEditing="GrdFoo_OnRowEditing"
OnRowCancelingEdit="GrdFoo_OnRowCancelingEdit"
OnRowUpdating="GrdFoo_OnRowUpdating"
OnRowDeleting="GrdFoo_OnRowDeleting"
DataKeyNames="ID">
<Columns>
<asp:TemplateField HeaderText="Name">
<ItemTemplate>
<asp:Label Text='<%#Eval("Name") %>' runat="server"/>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtName" Text='<%#Eval("Name") %>' runat="server"/>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Email">
<ItemTemplate>
<asp:Label Text='<%#Eval("Email") %>' runat="server"/>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtEmail" Text='<%#Eval("Email") %>' runat="server"/>
</EditItemTemplate>
</asp:TemplateField>
<asp:CommandField ShowEditButton="True"
ShowDeleteButton="True" buttontype="Image"
DeleteImageUrl="delete.png"
EditImageUrl="edit.png"
CancelImageUrl="cancel.png"
UpdateImageUrl="save.png"/>
</Columns>
</asp:GridView>

Retrieve links stored in DB and show it in GridView

Need a small help.
I'm having a table which is having links stored in some of the columns. I'm binding the table with a GridView present on my page. I need the cells of GridView to act as a link.
I have tried this code.
<asp:GridView runat="server" ID="gvAutomationTesting" CssClass="table table-bordered table-hover table-responsive" AutoGenerateColumns="false">
<Columns>
<asp:TemplateField HeaderText="Link 01" SortExpression="Link01">
<ItemTemplate>
<asp:LinkButton ID="lb01" runat="server" Text='<%# DataBinder.Eval(Container.DataItem, "Link01") %>' />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
The output which i'm getting is having a tag but without href attribute because of which even if i try to click it is not redirecting to the desired page.
hope below code snippets will help you, using templatefield you can assign the link button to grid column
<div>
<asp:GridView id="mygrid">
<asp:TemplateField headertext="number" datatype="string" filterexpression="CUSTOMERNUMBER"
sortexpression="CUSTOMERNUMBER">
<itemtemplate>
<asp:LinkButton ID="lnkbtn" runat="server" Text='<%# DataBinder.Eval(container.DataItem, "CUSTOMERNUMBER") %>' />
<%--CUSTOMERNUMBER is your DB column name--%>
</itemtemplate>
</asp:TemplateField>
<asp:boundfield headertext="Customer" datafield="CUSTOMERNAME" datatype="string" filterexpression="CUSTOMERNAME"
sortexpression="CUSTOMERNAME">
</asp:boundfield>
</asp:GridView>
</div>
Replace
<asp:LinkButton ID="lb01" runat="server" Text='<%# DataBinder.Eval(Container.DataItem, "Link01") %>' />
by
<a ID="lb01" runat="server" href='<%# DataBinder.Eval(Container.DataItem, "Link01")' ><%# DataBinder.Eval(Container.DataItem, "Link01") %> </a>

How to show and hide textbox in gridview on link button click

I have gridview,which has approve and reject button.When click on reject button i need to show textbox for comments else no.after enetering comments i have save it in data base.How to do this can any one help me
here is my code:
<asp:GridView ID="GridView1" runat="server" AllowPaging="True" AutoGenerateColumns="False" BackColor="White"
BorderColor="#CCCCCC" BorderStyle="None" BorderWidth="1px" CellPadding="4" ForeColor="Black"
GridLines="Horizontal" OnRowDataBound="GridView1_RowDataBound">
<Columns>
<asp:TemplateField HeaderText="Industrial Zone">
<ItemTemplate>
<asp:Label runat="server" ID="lblindzone" Text='<%# Eval("indzone") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="District">
<ItemTemplate>
<asp:Label runat="server" ID="lbldstr" Text='<%# Eval("dstr")%>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Industrial Area">
<ItemTemplate>
<asp:Label runat="server" ID="lblnmindar" Text='<%# Eval("nmindar")%>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Plot Number">
<ItemTemplate>
<asp:Label runat="server" ID="lblplno" Text='<%# Eval("plno")%>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Approve/Reject">
<ItemTemplate>
<asp:LinkButton ID="lnkApproved" runat="server" Text="Approve" OnClick="lnkApproved_Click"><img src="images/approve.png" style="width:20px;height:20px; margin:5px" title="Approve"/></asp:LinkButton>
<asp:LinkButton ID="lnkReject" runat="server" Text="Reject" OnClick="lnkReject_Click" OnClientClick="return showandhide(this)"><img src="images/reject.png" style="width:16px;height:16px; margin:5px" title="Reject"/></asp:LinkButton>
<asp:LinkButton ID="lnkviewdetails" runat="server" Text="View Details" OnClick="lnkviewdetails_Click"><img src="images/viewdetails.png" style="width:20px;height:20px; margin:5px" title="Details" /></asp:LinkButton>
<asp:TextBox ID="txtcomment" runat="server" style="display:none"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Status">
<ItemTemplate>
<asp:Label runat="server" ID="lblstatus" Text='<%# Eval("status")%>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
I am assuming you are doing it with only C# and no Javascript. to view or hide a specific textbox you should trigger a RowCommand Event of GridView:
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "viewhide")
{
GridViewRow gvr = (GridViewRow)(((LinkButton)e.CommandSource).NamingContainer);
TextBox tbComments = ((TextBox)gvr.FindControl("txtcomment"));
tbComments.Visible = true;
}
}
And this would be your ASPX Codebehind
<asp:LinkButton ID="lnkReject" runat="server" Text="Reject" OnClick="lnkReject_Click" CommandName="viewhide" OnClientClick="return showandhide(this)"><img src="images/reject.png" style="width:16px;height:16px; margin:5px" title="Reject"/></asp:LinkButton>
EDIT: Now You've changed the tag from C# to VB.NET which is not good. because i consumed all my time writing a c# code!

Cannot add row to gridview using emptydatatemplate

I have a Gridview in which I want to add a row when the grid is empty using EmptyDataTemplate. The problem is when the grid is empty and I try to add a row, no error occurs but the data row is not added. The Header row is added but not the data. When I put a breakpoint at the start of the RowCommand method, it is not triggered. I can't understand why the event will not trigger. When there is a row present the RowCommand event is triggered and I can add a second row but not an initial row.
This is my markup:
<asp:GridView ID="UserGroupGridView" runat="server" AutoGenerateColumns="False"
Caption="Group Information" CaptionAlign="Top" CssClass="grid"
AllowPaging="true" PageSize="10"
HorizontalAlign="Left" ShowHeaderWhenEmpty="True" ShowFooter="true" DataKeyNames="GroupID"
onrowcommand="UserGroupGridView_RowCommand">
<Columns>
<asp:TemplateField HeaderText="GroupID">
<ItemTemplate>
<asp:Label ID="uggvLblGroupID" runat="server" Text='<%# Bind("GroupID") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Group Name">
<HeaderTemplate> Group Name
<asp:ImageButton ID="uggvGroupFilter" runat="server" ImageUrl="Images/filter.png" OnClientClick="return ShowHideFilterTxtBox('uggvTxtNameFilter')" />
<asp:TextBox ID="uggvTxtNameFilter" runat="server" AutoPostBack="true" style="display:none;" ClientIDMode="Static" OnTextChanged="uggvGridFilter_TextChanged">
</asp:TextBox>
</HeaderTemplate>
<ItemTemplate>
<asp:Label ID="uggvLblGroupName" runat="server" Text='<%# Bind("GroupName") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="uggvTxtBoxEditGroupName" runat="server" Text='<%# Bind("GroupName") %>'></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldEditGroupName" ControlToValidate="uggvTxtBoxEditGroupName" runat="server"
ErrorMessage="Required field." ValidationGroup="EditGroupNameValidation" Display="Dynamic" CssClass="message-error">
</asp:RequiredFieldValidator>
<asp:RegularExpressionValidator ID="MaxValEditGroupName" ControlToValidate="uggvTxtBoxEditGroupName" runat="server"
ErrorMessage="Maximumn length is 80." ValidationGroup="EditGroupNameValidation" Display="Dynamic" CssClass="message-error"
ValidationExpression="^.{1,80}$" >
</asp:RegularExpressionValidator>
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox ID="uggvTxtBoxInsertGroupName" runat="server" Text='<%# Bind("GroupName") %>' ClientIDMode="Predictable"></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldInsertGroupName" ControlToValidate="uggvTxtBoxInsertGroupName" runat="server"
ErrorMessage="Required field." ValidationGroup="InsertGroupNameValidation" Display="Dynamic" CssClass="message-error">
</asp:RequiredFieldValidator>
<asp:RegularExpressionValidator ID="MaxValInsertGroupName" ControlToValidate="uggvTxtBoxInsertGroupName" runat="server"
ErrorMessage="Maximumn length is 80." ValidationGroup="InsertGroupNameValidation" Display="Dynamic" CssClass="message-error"
ValidationExpression="^.{1,80}$" >
</asp:RegularExpressionValidator>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Action" ItemStyle-Wrap="false" ItemStyle-HorizontalAlign="Center">
<ItemTemplate>
<asp:Button ID="uggvEditButton" runat="server" CausesValidation="False" CommandName="Edit"
Text="Edit" CssClass="gridActionbutton">
</asp:Button>
<asp:Button ID="uggvDeleteButton" runat="server" CausesValidation="False" CommandName="Delete"
Text="Delete" CssClass="gridActionbutton" OnClientClick="return confirm('Are you sure you want to delete this Group Information?')" >
</asp:Button>
</ItemTemplate>
<EditItemTemplate>
<asp:Button ID="uggvUpdateButton" runat="server" CausesValidation="True" ValidationGroup="EditGroupNameValidation" CommandName="Update"
Text="Update" CssClass="gridActionbutton"></asp:Button>
<asp:Button ID="uggvCancelButton" runat="server" CausesValidation="False" CommandName="Cancel"
Text="Cancel" CssClass="gridActionbutton"></asp:Button>
</EditItemTemplate>
<FooterTemplate>
<asp:Button ID="uggvAddButton" runat="server" CommandName="Add" Text="Add Group" Width="90%" CausesValidation="true"
CssClass="gridActionbutton" ValidationGroup="InsertGroupNameValidation">
</asp:Button>
</FooterTemplate>
</asp:TemplateField>
</Columns>
<EmptyDataTemplate>
<tr>
<th>GroupID</th>
<th>Group Name</th>
<th>Action</th>
</tr>
<tr>
<td colspan="3" style="text-align:center;">
No user-defined groups were found for you. Insert a group name and click the 'Add Group' Button.
</td>
</tr>
<tr>
<td></td>
<td>
<asp:TextBox ID="uggvTxtBoxInsertGroupName" runat="server" Width="90%"></asp:TextBox>
</td>
<td>
<asp:Button ID="uggvAddButtonEmpty" runat="server" CommandName="Add" Text="Add Group" Width="90%" CausesValidation="false"
CssClass="gridActionbutton">
</asp:Button>
</td>
</tr>
</EmptyDataTemplate>
</asp:GridView>
This is my RowCommand event:
protected void UserGroupGridView_RowCommand(object sender, GridViewCommandEventArgs e)
{
try
{
if (e.CommandName.Equals("Add"))
{
//Get the Footer controls that have the new entry data
Control tFooterControls = CommonMethods.getFooterControls(UserGroupGridView);
string tstrGroupName = (tFooterControls.FindControl("uggvTxtBoxInsertGroupName") as TextBox).Text;
string tstrLoginUserID = CommonMethods.ParseUserID(User.Identity.Name);
//Insert into the database
m_pagingClient.InsertGroup(m_strUserID, tstrGroupName, tstrLoginUserID);
//Rebind the grid with the new data
populateGroupGrid();
}
}
catch (Exception ex)
{
logger.ErrorException(ex.Message, ex);
Response.Redirect("~/Error.aspx?use=" + m_strUserType, false);
}
}
This grid is the parent grid of a nested grid. But I don't think that should matter.
Can anyone see what I am doing wrong?
Thanks.
UPDATE
Below is the validation that I had in the emptytemplatedata control
<EmptyDataTemplate>
<tr>
<th></th>
<th>GroupID</th>
<th>Group Name</th>
<th>Action</th>
</tr>
<tr>
<td colspan="4" style="text-align:center;">
No user-defined groups were found for you. Insert a group name and click the 'Add Group' Button.
</td>
</tr>
<tr>
<td></td>
<td></td>
<td>
<asp:TextBox ID="uggvTxtBoxInsertGroupName" runat="server" Width="90%"></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldInsertGroupNameEmpty" ControlToValidate="uggvTxtBoxInsertGroupName" runat="server"
ErrorMessage="Required field." ValidationGroup="InsertGroupNameValidationEmpty" Display="Dynamic" CssClass="message-error">
</asp:RequiredFieldValidator>
<asp:RegularExpressionValidator ID="MaxValInsertGroupNameEmpty" ControlToValidate="uggvTxtBoxInsertGroupName" runat="server"
ErrorMessage="Maximumn length is 80." ValidationGroup="InsertGroupNameValidationEmpty" Display="Dynamic" CssClass="message-error"
ValidationExpression="^.{1,80}$" >
</asp:RegularExpressionValidator>
</td>
<td>
<asp:Button ID="uggvAddButtonEmpty" runat="server" CommandName="Add" Text="Add Group" Width="90%" CausesValidation="true"
CssClass="gridActionbutton" ValidationGroup="InsertGroupNameValidationEmpty">
</asp:Button>
</td>
</tr>
</EmptyDataTemplate>
Why would the required validation trigger after I added a value in the text box?
UPDATE
This is my Page_Load code:
protected void Page_Load(object sender, EventArgs e)
{
try
{
if (!IsPostBack)
{
populateGroupGrid();
if (m_strUserID.Equals("Global"))
{
UserGroupGridView.Caption = "Global Group Information";
}
else
{
UserGroupGridView.Caption = "User Group Information";
}
}
}
catch (Exception ex)
{
logger.ErrorException(ex.Message, ex);
Response.Redirect("~/Error.aspx?use=" + m_strUserType, false);
}
}
This is my grid populate method.
private void populateGroupGrid()
{
try
{
HiddenField hdnFldFilter = (HiddenField)UserGroupGridWrapper.FindControl("uggvHidGridFilter");
m_strXmlTableData = m_pagingClient.GetGroups(m_strUserID);
m_dtGroupInfo = CommonMethods.ParseXML(m_strXmlTableData);
ViewState["GroupInfo"] = m_dtGroupInfo;
if (!String.IsNullOrEmpty(hdnFldFilter.Value))
{
m_dtGroupInfo.DefaultView.RowFilter = hdnFldFilter.Value;
}
UserGroupGridView.DataSource = m_dtGroupInfo;
UserGroupGridView.DataBind();
}
catch (Exception ex)
{
logger.ErrorException(ex.Message, ex);
Response.Redirect("~/Error.aspx?use=" + m_strUserType, false);
}
}
I fixed the problem by starting with the basic grid and adding everything back. It is working now but I don't know what in the gridview that was causing the problem. But it all works now.

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