I have defined a nested grid view in the following way.
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataSourceID="SqlDataSource1" OnRowDataBound="GridView1_RowDataBound" GridLines="None">
<Columns>
<asp:BoundField DataField="Date Of Transaction" HeaderText="Date Of Transaction"
SortExpression="Date Of Transaction" />
<asp:BoundField DataField="Invoice Number" HeaderText="Invoice Number" SortExpression="Invoice Number" />
<asp:BoundField DataField="totalAmount" HeaderText="totalAmount" ReadOnly="True"
SortExpression="totalAmount" />
<asp:TemplateField>
<ItemTemplate>
<asp:GridView ID="gridView2" runat="server" HorizontalAlign="Left" ShowHeader="false" GridLines="None" OnRowDataBound="gridView2_RowDataBound">
<Columns>
<asp:TemplateField ItemStyle-HorizontalAlign="Center" ItemStyle-Width="100px">
<ItemTemplate>
<asp:Button ID="Btn1" runat="server" Text="Download" OnClick="Btn1_Click"/>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:ComponentDBConnectionString %>"
SelectCommand="SelectUserPreviousHistory" SelectCommandType="StoredProcedure">
<SelectParameters>
<asp:Parameter DefaultValue="XYZZ" Name="userName" Type="String" />
</SelectParameters>
</asp:SqlDataSource>
The screenshot of the output is here. As you can see i have a "Download" button in each row of the child gridview (i.e., gridView2) but I want the download button to be last column but .net is rendering it to be the first column.
How can I do it?
More over gridview2 datasource is arraylist. Here is the code
gridView2.DataSource = titlesArrayList;
gridView2.DataBind();
Please help me
Thanks in anticipation
Why don't you simply add a Label before the Donwload-Button in the ItemTemplate? You could set the Label's Text in RowDataBound(gridView2_DataBound).
Edit: to show the header columns of the nested gridview in the header of the outer gridview, you could set ShowHeader="false" in the inner grid and use a HeaderTemplate with two labels for "Software Titles" and "Download here" and appropriate CSS-Styles to fit to the inner grid.
Edit:
Here is a working test-page. Pick the parts you didn't understand:
aspx:
<asp:GridView ID="GrdTransaction" runat="server" OnRowDataBound="GrdTransaction_RowDataBound" AutoGenerateColumns="false">
<Columns>
<asp:BoundField DataField="DateOfTransaction" HeaderText="Date Of Transaction"
SortExpression="DateOfTransaction" />
<asp:TemplateField>
<HeaderTemplate>
<table width="100%" cellspacing="0" cellpadding="0" border="0">
<tr>
<td><asp:Label ID="LblFileNameHeader" Text="File-Name" runat="server" /></td><td><asp:Label ID="LblDownloadHeader" Text="Download file" runat="server" /></td>
</tr>
</table>
</HeaderTemplate>
<ItemTemplate>
<asp:GridView ID="GrdDocument" runat="server" ShowHeader="false" GridLines="None" AutoGenerateColumns="false"
OnRowCommand="GrdDocument_RowCommand" OnRowDataBound="GrdDocument_RowDataBound">
<Columns>
<asp:TemplateField ItemStyle-HorizontalAlign="Center" ItemStyle-Width="100px">
<ItemTemplate>
<asp:Label ID="LblFileName" Text='<%# Eval("Doc")%>' runat="server" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField ItemStyle-HorizontalAlign="Center" ItemStyle-Width="100px">
<ItemTemplate>
<asp:Button ID="BtnDownload" runat="server" CommandArgument='<%# Eval("Doc")%>' CommandName="Download" Text="Download" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Codebehind(converted from vb.net to c#):
public class WebForm1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack) {
this.GrdTransaction.DataSource = GetOuterGridSource();
this.GrdTransaction.DataBind();
}
}
private DataTable GetOuterGridSource()
{
DataTable tbl = new DataTable();
tbl.Columns.Add(new DataColumn("ID", typeof(Int32)));
tbl.Columns.Add(new DataColumn("DateOfTransaction", typeof(DateTime)));
DataRow row = tbl.NewRow();
row["ID"] = 1;
row["DateOfTransaction"] = System.DateTime.Now;
tbl.Rows.Add(row);
row = tbl.NewRow();
row["ID"] = 2;
row["DateOfTransaction"] = System.DateTime.Now;
tbl.Rows.Add(row);
row = tbl.NewRow();
row["ID"] = 2;
row["DateOfTransaction"] = System.DateTime.Now;
tbl.Rows.Add(row);
return tbl;
}
private DataTable GetNestedGridSource()
{
DataTable tbl = new DataTable();
tbl.Columns.Add(new DataColumn("ID", typeof(Int32)));
tbl.Columns.Add(new DataColumn("Doc", typeof(string)));
DataRow row = tbl.NewRow();
row["ID"] = 1;
row["Doc"] = "Smart Defrag";
tbl.Rows.Add(row);
row = tbl.NewRow();
row["ID"] = 2;
row["Doc"] = "Visio Viewer";
tbl.Rows.Add(row);
row = tbl.NewRow();
row["ID"] = 2;
row["Doc"] = "Rapid Typing";
tbl.Rows.Add(row);
return tbl;
}
protected void GrdTransaction_RowDataBound(object sender, System.Web.UI.WebControls.GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow) {
dynamic row = ((DataRowView)e.Row.DataItem).Row;
dynamic GrdDocument = (GridView)e.Row.FindControl("GrdDocument");
GrdDocument.DataSource = GetNestedGridSource();
GrdDocument.DataBind();
GrdDocument.RowCommand += GrdDocument_RowCommand;
}
}
protected void GrdDocument_RowDataBound(object sender, System.Web.UI.WebControls.GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow) {
dynamic row = ((DataRowView)e.Row.DataItem).Row;
dynamic LblFileName = (Label)e.Row.FindControl("LblFileName");
LblFileName.Text = row("Doc").ToString;
}
}
protected void GrdDocument_RowCommand(object sender, System.Web.UI.WebControls.GridViewCommandEventArgs e)
{
if (e.CommandName == "Download") {
dynamic docName = e.CommandArgument.ToString();
}
}
public WebForm1()
{
Load += Page_Load;
}
}
I have set the LblFileName's Text poperty in GrdDocument_RowDataBound. That is redundant because i've always used eval on the aspx-page. I wanted to show both ways for the sake of completeness.
This is result:
in your gridView2, set AutoGenerateColumns="False" and add a asp:BoundField before the asp:TemplateField
Are you sure there is no missing code in your snippet?
<asp:GridView ID="gridView2" runat="server" HorizontalAlign="Left" ShowHeader="false" GridLines="None" OnRowDataBound="gridView2_RowDataBound" AutoGenerateColumns="False">
<Columns>
<asp:BoundField HeaderText="" DataField="ToString" />
<asp:TemplateField ItemStyle-HorizontalAlign="Center" ItemStyle-Width="100px">
<ItemTemplate>
<asp:Button ID="Btn1" runat="server" Text="Download" OnClick="Btn1_Click"/>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Related
I have a problem with asp.net gridviewpager. When i click pager any page it routes to OnRowCommand event. I am waiting to route OnPageIndexChanging
I have define my gridview like this.
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false" DataKeyNames="Id"
GridLines="None" PageSize="4" AllowPaging="True" EmptyDataText="No record found"
OnPageIndexChanging="OnPaging" OnRowDeleting="GridView1_RowDeleting" OnRowCommand="RowCommand"
CssClass="mGrid" PagerStyle-CssClass="pgr" AlternatingRowStyle-CssClass="alt">
<Columns>
<asp:BoundField DataField="Id" HeaderText="Id" />
<asp:BoundField DataField="Baslik" HeaderText="Baslik" />
<asp:BoundField DataField="KisaAciklama" HeaderText="Kısa Acıklama" />
<asp:TemplateField HeaderText="Güncelle">
<ItemTemplate>
<asp:LinkButton runat="server" ID="lnkView" CommandArgument='<%#Eval("Id") %>' CommandName="VIEW">Güncelle</asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Sil">
<ItemTemplate>
<asp:LinkButton runat="server" ID="lnkDelete" CommandArgument='<%#Eval("Id") %>'
CommandName="DELETE">Sil</asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
<%----%>
</Columns>
</asp:GridView>
Also my back-end code is
protected void RowCommand(object sender, GridViewCommandEventArgs e)
{
LinkButton lnkView = (LinkButton)e.CommandSource;
string Id = lnkView.CommandArgument;
if (e.CommandName == "VIEW")
{
Response.Redirect("/Views/AdminPages/Kayit.aspx?cmd=Update&id="+Id);
}
else if (e.CommandName == "DELETE")
{
kayitService.DeleteKayit(Convert.ToInt32(Id));
}
}
protected void OnPaging(object sender, GridViewPageEventArgs e)
{
GridView1.PageIndex = e.NewPageIndex;
GridView1.DataBind();
}
Please try this
<asp:GridView ID="Gridview1" runat="server" AutoGenerateColumns="False" BackColor="White"
BorderColor="#3366CC" BorderStyle="None" BorderWidth="1px" CellPadding="4"
onpageindexchanging="gvPerson_PageIndexChanging"
onrowcancelingedit="gvPerson_RowCancelingEdit"
onrowdatabound="gvPerson_RowDataBound" onrowdeleting="gvPerson_RowDeleting"
onrowediting="gvPerson_RowEditing" onrowupdating="gvPerson_RowUpdating"
onsorting="gvPerson_Sorting">
<asp:BoundField DataField="Id" HeaderText="Id" />
<asp:BoundField DataField="Baslik" HeaderText="Baslik" />
<asp:BoundField DataField="KisaAciklama" HeaderText="Kısa Acıklama" />
<asp:TemplateField HeaderText="Güncelle">
<ItemTemplate>
<asp:LinkButton runat="server" ID="lnkView" CommandArgument='<%#Eval("Id") %>' CommandName="VIEW">Güncelle</asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Sil">
<ItemTemplate>
<asp:LinkButton runat="server" ID="lnkDelete" CommandArgument='<%#Eval("Id") %>'
CommandName="DELETE">Sil</asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
<%----%>
</Columns>
Back-end code may be :
protected void gvPerson_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
// Set the index of the new display page.
Gridview1.PageIndex = e.NewPageIndex;
// Rebind the GridView control to
// show data in the new page.
BindGridView();
}
According to my opinion the code which I mentioned above is the most appropriate code for Paging.
I am trying to calculate the date difference between two dates and want to show them in grid. I have created a table in the grid and the results can be printer there.
My RowDataBound is calculating everything but don't know how to print the results.
protected void grdADR_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
Label lblADRYear = (Label)e.Row.FindControl("lblADRYear");
Label lblBRCIDADR = (Label)e.Row.FindControl("lblBRCIDADR");
DataTable dt = new DataTable();
string strQuery = "Select ADR_TYPE,DatePART(dayofyear,Document_Date) AS DayOfTheYearADR,Document_Date From ADR Where BRCID = '" + lblBRCIDADR.Text.ToString() + "'"
+ " AND CAST(YEAR(Document_Date) AS VARCHAR(4)) = '" + lblADRYear.Text.ToString() + "' Order by DayOfTheYearADR";
dt = objAccess.GetDataTable(strQuery);
if (dt != null)
{
if (dt.Rows.Count > 0)
{
int DayMarker = 0;
int LastDay = 0;
List<Label> labels = new List<Label>();
for (int rcnt = 0; rcnt < dt.Rows.Count; rcnt++)
{
DataRow dr = dt.Rows[rcnt];
Label lblADRTimeLineStart = new Label();
lblADRTimeLineStart.ForeColor = System.Drawing.Color.Red;
int RowDay = int.Parse(dr["DayOfTheYearADR"].ToString());
if (LastDay != RowDay)
{
Label lblEmptyBlock = new Label();
lblADRTimeLineStart.ForeColor = System.Drawing.Color.Blue;
lblEmptyBlock.Width = (RowDay - DayMarker) * 3;
labels.Add(lblEmptyBlock);
Label lblADRBlock = new Label();
lblADRTimeLineStart.ForeColor = System.Drawing.Color.Green;
lblADRBlock.Width = 3;
labels.Add(lblADRBlock);
DayMarker = RowDay + 3;
}
LastDay = RowDay;
}
}
}
}
}
ASPX File
<asp:GridView ID="grdADR" runat="server" DataSource='<%# functADRTimeLine(Eval("Month").ToString()) %>' AutoGenerateColumns="false" ShowHeader="true" AllowPaging="false" Width="1260px" GridLines="Both"
BorderWidth="0" BorderColor="#839168" BorderStyle="Solid" CellPadding="0" BackColor="white" OnRowDataBound="grdADR_RowDataBound">
<Columns>
<asp:TemplateField Visible="false">
<HeaderTemplate>BRCID</HeaderTemplate>
<ItemTemplate>
<asp:Label ID="lblBRCIDADR" runat="server" Text='<%# Bind("BRCID") %>'></asp:Label>
</ItemTemplate>
<ItemStyle Width="0px" Wrap="true" BorderColor="black" BorderStyle="Dotted" BorderWidth="1" HorizontalAlign="Center" />
<HeaderStyle BorderColor="black" BorderStyle="Outset" BorderWidth="1" HorizontalAlign="Center" />
</asp:TemplateField>
<asp:TemplateField Visible="false">
<HeaderTemplate>Year</HeaderTemplate>
<ItemTemplate>
<asp:Label ID="lblADRYEAR" runat="server" Text='<%# Bind("ADR_YEAR") %>'></asp:Label>
</ItemTemplate>
<ItemStyle Width="0px" Wrap="true" BorderColor="black" BorderStyle="Dotted" BorderWidth="1" HorizontalAlign="Center" />
<HeaderStyle BorderColor="black" BorderStyle="Outset" BorderWidth="1" HorizontalAlign="Center" />
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<table cellpadding="0" cellspacing="0" border="0">
<tr>
<td style="width: 150px">
<%--HERE I WANT TO PRINT MY RESULTS.--%>
</td>
<td style="width: 1101px"></td>
</tr>
</table>
</ItemTemplate>
</asp:TemplateField>
</Columns>
<HeaderStyle Height="25px" HorizontalAlign="Center" BackColor="#a8b194" />
<RowStyle CssClass="grd_RowStyle" BorderColor="black" BorderStyle="Dotted" BorderWidth="1" Wrap="true" />
</asp:GridView>
There are many options for you to print the text
One option would be
Add a placeholder control in where you want the labels to be printed
<asp:PlaceHolder ID="placeHolderLabels" runat="server"></asp:PlaceHolder>
In the codebehind, find this placeholder like this
PlaceHolder placeHolderLabels= (PlaceHolder)e.Row.FindControl("placeHolderLabels");
Then add your labels to this placeholder control using the following code
placeHolderLabels.Controls.Add(lblEmptyBlock);
placeHolderLabels.Controls.Add(lblADRBlock);
Another option is, since you are printing table like structure, you can add a datalist/gridview/repeater control where you want to print the labels. Then you can bind your calculated list to this control, which is more cleaner
I am having issue when updating gridview! everything is seems to be working. but when i hit finish editing the data will not save!
but when i click edit the correct fields prompt me to enter new value but it wont save!
here is my asp
<asp:GridView ID="GridView1" runat="server" CssClass="report"
AutoGenerateColumns="False" onrowediting="GridView1_RowEditing"
DataKeyNames="TimeID" onrowupdating="GridView1_RowUpdating"
onrowcommand="GridView1_RowCommand"
onrowcancelingedit="GridView1_RowCancelingEdit">
<Columns>
<asp:BoundField DataField="date" Visible="true" ReadOnly="true" HeaderText="Date" />
<asp:BoundField DataField="Description" HeaderText="Stage Description" ReadOnly="True" />
<asp:TemplateField HeaderText="Start Time">
<ItemTemplate>
<asp:Label ID="Label7" runat="server" Text='<%# ConvertToShotTime(Eval("StartTime")) %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtStartTime" ValidationGroup="1" Width="90px" class="TimeEntry" runat="server" Text='<%# ConvertToShotTime(Eval("StartTime")) %>'></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator6" ControlToValidate="txtStartTime" runat="server" ErrorMessage="RequiredFieldValidator"></asp:RequiredFieldValidator>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="End Time">
<ItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%# ConvertToShotTime(Eval("EndTime")) %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtEndTime" class="TimeEntry" ValidationGroup="1" Width="90px" runat="server" Text='<%# ConvertToShotTime(Eval("EndTime")) %>'></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator66" ControlToValidate="txtEndTime" runat="server" ErrorMessage="RequiredFieldValidator"></asp:RequiredFieldValidator>
</EditItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="TimeInHours" HeaderText="Time Time (Hours)" ReadOnly="True" />
<asp:CommandField ShowEditButton="true" ShowCancelButton="true"
ButtonType="Image" EditImageUrl="~/images/edit_record.jpg"
CancelImageUrl="~/images/edit_no.jpg"
UpdateImageUrl="~/images/update_record.jpg" />
<asp:TemplateField ShowHeader="False">
<ItemTemplate>
<asp:ImageButton ID="lnbCopy" runat="server" AlternateText="Delete"
CommandName="DeleteRecord" CommandArgument='<%# Bind("TimeID") %>' OnClientClick="return confirm('Are you sure you want to delete this row?');" ImageUrl="~/images/delete_record.jpg" />
</ItemTemplate>
<EditItemTemplate>
<asp:Label ID="lblTimeID" runat="server" Text='<%# Eval("TimeID") %>'></asp:Label>
</EditItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
here is what i have done in behind code
protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e) {
GridView1.EditIndex = e.NewEditIndex;
loadTable();
}
protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e) {
GridView1.EditIndex = -1;
loadTable();
}
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e) {
GridViewRow row = GridView1.Rows[e.RowIndex] as GridViewRow;
var StartTime = row.FindControl("txtStartTime") as TextBox;
var EndTime = row.FindControl("txtEndTime") as TextBox;
var id = row.FindControl("lblTimeID") as Label;
SqlConnection conn = new SqlConnection(conStr.GetConnectionString("myServer1"));
SqlCommand comm = new SqlCommand();
comm.CommandText = "UPDATE CDSTimeSheet SET StartTime = #StartTime, EndTime = #EndTime ,timeElapsed = datediff(minute,#startTime , #EndTime), timeInSeconds = datediff(second,#startTime , #EndTime) WHERE TimeID = #id";
comm.Connection = conn;
comm.Parameters.AddWithValue("#id", id.Text);
comm.Parameters.AddWithValue("#StartTime", StartTime.Text);
comm.Parameters.AddWithValue("#EndTime", EndTime.Text);
conn.Open();
comm.ExecuteNonQuery();
conn.Close();
GridView1.EditIndex = -1;
loadTable();
}
what am i doing wrong?
It sounds a lot like you are not calling DataBind on your grid after updating the underlying data. After you perform the update (possibly within the loadTable method that I see referenced up there), call
GridView1.DataBind();
That should refresh the data in the grid.
After your comments, I see that you're not using the NewValues collection in the GridViewUpdateEventArgs parameter to get the actual incoming, updated field values. Try this:
String StartTime = e.NewValues["StartTime"].ToString();
String EndTime = e.NewValues["EndTime"].ToString();
String id = e.Keys[0].ToString();
Note that these variables are strings now, not TextBoxs, so you don't need to add ".Text" on them when you add them as parameters.
Handle the postback, basically if you fill the grid view in each postback you are re filling the gridview with old data, that's why you retrieve data with no changes (remember after Update button this trigger a postback). So, in case this is your case, try this.
if(!this.IsPostback)
{
(Method that fills your GridView)
}
I have a GridView like so:
<asp:GridView runat="server" ID="grdPractices" PageSize="10" AutoGenerateColumns="False" DataKeyNames="Id"
CssClass="linkGrid" AllowSorting="True" OnSorting="grdPractices_OnSorting" OnRowDataBound="grdPractices_OnRowDataBound"
OnRowEditing="grdPractices_OnRowEditing" OnRowCancelingEdit="grdPractices_OnRowCancelingEdit" OnRowUpdating="grdPractices_OnRowUpdating">
<Columns>
<asp:BoundField DataField="Name" HeaderText="Name" meta:resourcekey="PracticeName" ReadOnly="True" SortExpression="Name" ItemStyle-Width="400px" />
<asp:BoundField DataField="Code" HeaderText="Code" meta:resourcekey="Code" ReadOnly="True" SortExpression="Code" ItemStyle-Width="200px" />
<asp:TemplateField meta:resourcekey="SiteName" ItemStyle-Width="200px" SortExpression="SiteName">
<ItemTemplate>
<asp:Literal runat="server" Text='<%# Eval("SiteName") %>' />
</ItemTemplate>
<EditItemTemplate>
<asp:DropDownList runat="server" ID="lstSites" />
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField meta:resourcekey="NumOfUsers" ItemStyle-Width="200px" SortExpression="NumOfUsers">
<ItemTemplate>
<asp:LinkButton runat="server" OnCommand="OnLinkButtonCommand" CommandName="ViewUsers" Text='<%# Eval("NumOfUsers") %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:CommandField ShowDeleteButton="False" ShowCancelButton="True"
ShowInsertButton="False" ShowEditButton="True" EditText="Edit"
CancelText="Cancel" UpdateText="Update" meta:resourcekey="Edit" ItemStyle-Width="200px" />
</Columns>
</asp:GridView>
and here is the code for the OnRowEditing event:
protected void grdPractices_OnRowEditing(object sender, GridViewEditEventArgs e)
{
this.grdPractices.EditIndex = e.NewEditIndex;
var sitesDropDown = this.grdPractices.Rows[e.NewEditIndex].Controls[0].FindControl("lstSites") as DropDownList;
if (sitesDropDown == null)
{
return;
}
}
My problem is that I cannot get a hold of the lstSites control, which lives in the EditTemplate. I've tried using the following:
this.grdPractices.Rows[e.NewEditIndex].Controls[0].FindControl("lstSites")
as DropDownList;
this.grdPractices.Rows[e.NewEditIndex].FindControl("lstSites") as
DropDownList;
this.grdPractices.Rows[e.NewEditIndex].FindControlRecursive("lstSites")
as DropDownList;
The result is always the same, a NULL is returned.
How on earth are you supposed to get a control in a row when in the OnRowEditing event?
OK, what I was not doing, after this line:
this.grdPractices.EditIndex = e.NewEditIndex;
was then rebinding the grid's data. So after rebinding the data, and then calling:
var sitesDropDown = this.grdPractices.Rows[e.NewEditIndex].FindControlRecursive("lstSites") as DropDownList;
I am now able to interact with the siteDropDown variable since it now contains a reference to the lstSites control.
Try to use GridViewRow as following...
protected void grd_RowEditing(object sender, GridViewEditEventArgs e)
{
GridViewRow selectRow = grd.Rows(e.NewEditIndex);
DropDownList sitesDropDown =(DropDownList)selectRow.Cells[2].FindControl("lstSites");
}
work on asp.net vs05.I have a grid
<asp:GridView ID="GridView3" runat="server" AutoGenerateColumns="False"
DataKeyNames="StudentID" OnSelectedIndexChanged="GridView3_SelectedIndexChanged"
OnRowDataBound="GridView3_RowDataBound">
<Columns>
<asp:BoundField DataField="StudentID" HeaderText="StudentID" ReadOnly="True"
SortExpression="StudentID" />
<asp:BoundField DataField="StudentName" HeaderText="StudentName" />
<asp:TemplateField HeaderText="DivisionName">
<EditItemTemplate>
<asp:TextBox ID="TextBox1" runat="server"
Text='<%# Bind("StudentName") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:DropDownList ID="DropDownList1" runat="server"
Width="160px"></asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
<asp:ButtonField ButtonType="Button" CommandName="Select" HeaderText="Update"
Text="Update" />
</Columns>
</asp:GridView>
Using The button Click i want to save value on database.But i can not read value from the dropdownlist
protected void GridView3_SelectedIndexChanged(object sender, EventArgs e)
{
GridViewRow selectRow = GridView3.SelectedRow;
String ID = selectRow.Cells[0].Text;
String Name = selectRow.Cells[1].Text;
//String Dis = selectRow.Cells[2].Text;
String Dis =
((DropDownList)sender).FindControl("DropDownList1").ToString();
//**want to get this value**
}
How can i get ddl selected value?i want to put the object of a class on ddl .Bellow code work on desktop ,Want same thing on web.
DropDownList1.DisplayMember = "CommercialRegionName";
foreach (class oItem in _collection)
{
DropDownList1.Items.Add(oItem);
//**want to save object,Not any object item like:oItem.Name.**
}
protected void GridView3_SelectedIndexChanged(object sender, EventArgs e)
{
GridViewRow selectRow = GridView3.SelectedRow;
String ID = selectRow.Cells[0].Text;
String Name = selectRow.Cells[1].Text;
//String Dis = selectRow.Cells[2].Text;
//PROBABLY YOU WANT TO GET ITEM FROM SELECTED ROW'S DROPDOWN
var ddl = (selectRow).FindControl("DropDownList1") as DropdownList;
if(dis!=null){
var s=ddl.SelectedItem.Text;
}
}