Two Item templates in one Template field? - c#

Is it possible to have two item templates in one template field? This is my current code and its not working because when I run it e.Row.FindControl("gvQuoteItems") always returns null:
ASPX:
<asp:TemplateField ItemStyle-Width="50px">
<ItemTemplate>
<img alt="" style="cursor: pointer" src="images/plus.png" />
<asp:Panel ID="pnlQuoteItems" runat="server" Style="display: none">
<asp:GridView ID="gvQuoteItems" runat="server" AutoGenerateColumns="false" CssClass="GridView" OnRowDeleting="gvQuote_RowDeleting" ShowFooter="True">
<Columns>
<asp:CommandField ShowDeleteButton="True" />
<asp:BoundField DataField="QuoteItemID" HeaderText="QuoteItemID" SortExpression="QuoteItemID" Visible="false" />
<asp:BoundField DataField="Category" HeaderText="Category" SortExpression="Category" Visible="false" />
<asp:BoundField DataField="Cover" HeaderText="Cover" SortExpression="Cover" />
<asp:BoundField DataField="CoverType" HeaderText="Cover Type" SortExpression="CoverType" Visible="false" />
<asp:BoundField DataField="SumInsured" HeaderText="Sum Insured" SortExpression="SumInsured" />
<asp:BoundField DataField="Rate" HeaderText="Rate" SortExpression="Rate" />
<asp:BoundField DataField="AnnualPremium" HeaderText="Annual Premium" SortExpression="AnnualPremium" />
<asp:BoundField DataField="MonthlyPremium" HeaderText="Monthly Premium" SortExpression="MonthlyPremium" />
</Columns>
<FooterStyle BackColor="#022439" Font-Bold="True" ForeColor="White" />
<EmptyDataTemplate>
No Data To Display!
</EmptyDataTemplate>
</asp:GridView>
</asp:Panel>
</ItemTemplate>
<ItemTemplate>
<img alt="" style="cursor: pointer" src="images/plus.png" />
<asp:Panel ID="pnlMotorQuoteItems" runat="server" Style="display: none">
<asp:GridView ID="gvMotorQuoteItems" runat="server" AutoGenerateColumns="false" CssClass="GridView" OnRowDeleting="gvQuote_RowDeleting" ShowFooter="True">
<Columns>
<asp:CommandField ShowDeleteButton="True" />
<asp:BoundField DataField="QuoteItemID" HeaderText="QuoteItemID" SortExpression="QuoteItemID" Visible="false" />
<asp:BoundField DataField="Category" HeaderText="Category" SortExpression="Category" Visible="false" />
<asp:BoundField DataField="Year" HeaderText="Year" SortExpression="Year" />
<asp:BoundField DataField="MakeAndModel" HeaderText="Make And Model" SortExpression="MakeAndModel" />
<asp:BoundField DataField="NCB" HeaderText="NCB" SortExpression="NCB" />
<asp:BoundField DataField="Cover" HeaderText="Cover" SortExpression="Cover" />
<asp:BoundField DataField="CoverType" HeaderText="Cover Type" SortExpression="CoverType" Visible="false" />
<asp:BoundField DataField="SumInsured" HeaderText="Sum Insured" SortExpression="SumInsured" />
<asp:BoundField DataField="Rate" HeaderText="Rate" SortExpression="Rate" />
<asp:BoundField DataField="AnnualPremium" HeaderText="Annual Premium" SortExpression="AnnualPremium" />
<asp:BoundField DataField="MonthlyPremium" HeaderText="Monthly Premium" SortExpression="MonthlyPremium" />
</Columns>
<FooterStyle BackColor="#022439" Font-Bold="True" ForeColor="White" />
<EmptyDataTemplate>
No Data To Display!
</EmptyDataTemplate>
</asp:GridView>
</asp:Panel>
</ItemTemplate>
</asp:TemplateField>
Code-behind:
if (e.Row.RowType == DataControlRowType.DataRow)
{
int categoryID = int.Parse(gvQuote2.DataKeys[e.Row.RowIndex].Value.ToString());
if (categoryID == 16)
{
GridView gvQuoteItems = e.Row.FindControl("gvMotorQuoteItems") as GridView;
gvQuoteItems.DataSource = _QuoteBLL._GetMotorQuoteItemsDataTable(quote.QuoteID);
gvQuoteItems.DataBind();
}
else
{
GridView gvQuoteItems = e.Row.FindControl("gvQuoteItems") as GridView;
gvQuoteItems.DataSource = _QuoteBLL._GetQuoteItemsDataTable(quote.QuoteID, categoryID);
gvQuoteItems.DataBind();
}
}
When I try to run the above as it is, e.Row.FindControl("gvQuoteItems") always returns null. But if I remove the second ItemTemplate, it works fine. But you see, one of the rows has different columns (gvMotorQuoteItems). How can I go about this?

You cannot override the same template two times. However you can have two placeholeholders within the template and show/hide only the relevant one via Visible property.
<ItemTemplate>
<asp:PlaceHolder ID="phFirst" runat="server">
... pnlQuoteItems
</asp:PlaceHolder>
<asp:PlaceHolder ID="phSecond" runat="server">
... pnlMotorQuoteItems
</asp:PlaceHolder>
</ItemTemplate>

Related

How can I find a BoundField inside a GridView by DataField?

I want to change the CSS class behind the tenth BoundField inside my GridView, but I'd like to find it by DataField (i.e., use a string as index).
protected void gdDeliveryDates_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
string DeliveryDue = DataBinder.Eval(e.Row.DataItem, "DeliveryDue").ToString();
((LinkButton) e.Row.FindControl("PostDelivery")).Enabled = !String.IsNullOrEmpty(DeliveryDue);
//e.Row.Cells[9].CssClass= "badge";
}
}
In the code above I have commented out the only solution I've found so far, which to me is unacceptable because a column number (i.e., column 9 as specified above) is very volatile. I would prefer to find the column by DataField (a string, in this case, "MailCount" as you'll see in the grid declaration further ahead). Below is what my grid looks like:
<asp:GridView ID="gdDeliveryDates" runat="server" AllowPaging="False" AllowSorting="True" DataSourceID="odsDeliveryDates" AutoGenerateColumns="False" CssClass="table table-striped table-bordered table-hover" OnRowCommand="gdDeliveryDates_RowCommand" OnSelectedIndexChanged="gdDeliveryDates_SelectedIndexChanged" DataKeyNames="PackageOfferedID, PackageID, PostageID, PackageNumber, PackageTitle, PostageName, Section, PostageStart, PostageEnd, DeliveryDue, LName, MailCount, Location" OnRowDataBound="gdDeliveryDates_RowDataBound" >
<Columns>
<asp:BoundField DataField="PackageID" HeaderText="PackageID" Visible="False" ReadOnly="True" SortExpression="PackageID" />
<asp:BoundField DataField="PackageOfferedID" HeaderText="PackageOfferedID" Visible="False" ReadOnly="True" SortExpression="PackageOfferedID" />
<asp:BoundField DataField="PostageID" HeaderText="PostageID" Visible="False" ReadOnly="True" SortExpression="PostageID" />
<asp:BoundField DataField="PackageNumber" HeaderText="Package" Visible="True" ReadOnly="True" SortExpression="PackageNumber" HeaderStyle-CssClass="visible-xs visible-sm visible-md visible-lg" ItemStyle-CssClass="visible-xs visible-sm visible-md visible-lg" />
<asp:BoundField DataField="PostageName" HeaderText="Postage" ReadOnly="True" SortExpression="PostageName" HeaderStyle-CssClass="visible-sm visible-md visible-lg" ItemStyle-CssClass="visible-sm visible-md visible-lg"/>
<asp:BoundField DataField="Section" HeaderText="Section" ReadOnly="True" SortExpression="Section" HeaderStyle-CssClass="visible-xs visible-sm visible-md visible-lg" ItemStyle-CssClass="visible-xs visible-sm visible-md visible-lg" />
<asp:BoundField DataField="PostageStartDate" HeaderText="Start Date" ReadOnly="True" SortExpression="PostageStartDate" DataFormatString="{0:MM/dd/yyyy}" HeaderStyle-CssClass="visible-md visible-lg" ItemStyle-CssClass="visible-md visible-lg" />
<asp:BoundField DataField="PostageEndDate" HeaderText="End Date" ReadOnly="True" SortExpression="PostageEndDate" DataFormatString="{0:MM/dd/yyyy}" HeaderStyle-CssClass="visible-md visible-lg" ItemStyle-CssClass="visible-md visible-lg" />
<asp:BoundField DataField="DeliveryDueDate" HeaderText="Delivery Due" ReadOnly="True" SortExpression="DeliveryDueDate" DataFormatString="{0:MM/dd/yyyy}" HeaderStyle-CssClass="visible-xs visible-sm visible-md visible-lg" ItemStyle-CssClass="visible-xs visible-sm visible-md visible-lg" />
<asp:BoundField DataField="MailCount" HeaderText="#" Visible="True" ReadOnly="True" SortExpression="MailCount" HeaderStyle-CssClass="visible-lg" ItemStyle-CssClass="visible-lg" />
<asp:TemplateField ShowHeader="False">
<ItemTemplate>
<asp:LinkButton ID="PostDelivery" runat="server" CausesValidation="false" CommandName="Add"
Text="Post Delivery" CommandArgument='<%# DataBinder.Eval(Container, "RowIndex") %>'
CssClass="buttonLayout" />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="LName" HeaderText="LName" Visible="False" ReadOnly="True" SortExpression="LName" />
<asp:BoundField DataField="Location" HeaderText="Location" Visible="False" ReadOnly="True" SortExpression="Location" />
</Columns>
</asp:GridView>
This is not possible but you can try this method:
public int FindIndexByDataField(this GridView gv, string datafieldname)
{
int index = -1, cnum = 0;
foreach (DataControlField col in gv.Columns)
{
if (col is BoundField)
{
BoundField coll = (BoundField)gv.Columns[cnum];
if (coll.DataField == datafieldname)
{
index = cnum;
break;
}
}
cnum++;
}
return index;
}
And call above method like this:
e.Row.Cells[FindIndexByDataField("MailCount")].CssClass= "badge";

Not able to access hyperlink column inside gridview from code behind

I want to access the HyperLinkField column of the GridView from code behind but I am unable to do so.
I have the column in my dataset but I am still not able to use it.
My HyperLinkField column is named Status.
Here is what I tried:
UltraWebGrid1.DataSource = ObjPriDsGrid;
UltraWebGrid1.DataBind();
string StrPriStatus = "";
for (int IntPriI = 0; IntPriI < UltraWebGrid1.Rows.Count; IntPriI++)
{
if (UltraWebGrid1.Rows[IntPriI].Cells[6].Text.Trim() != null)
{
StrPriStatus = UltraWebGrid1.Rows[IntPriI].Cells[6].Text.Trim();
}
else
{
}
if (StrPriStatus == "5")
{
UltraWebGrid1.Rows[IntPriI].Cells[8].Text = ""; // Not getting status column here
}
}
Here is my GridView:
<asp:GridView ID="UltraWebGrid1" ShowHeader="true" runat="server" AutoGenerateColumns="false"
DataKeyNames="mkey" OnRowDataBound="Grid_RowDataBound" Width="98%" Height="30%"
PageSize="10" AllowPaging="true" OnPageIndexChanging="Grid1_PageIndexChanging"
ShowFooter="true" CssClass="Grid">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<img alt="" style="cursor: pointer" src="../../../Images/plus.png" />
<asp:Panel ID="pnlGrid" runat="server" Style="display: none">
<asp:GridView ID="Grid2" runat="server" AutoGenerateColumns="false" Width="600px"
CssClass="ChildGrid">
<Columns>
<asp:BoundField ItemStyle-Width="80px" DataField="RefMkey" HeaderText="Mkey" />
<asp:BoundField ItemStyle-Width="150px" DataField="CurrentUser" HeaderText="Current User" />
<asp:BoundField ItemStyle-Width="180px" DataField="Department" HeaderText="Current Department" />
<asp:BoundField ItemStyle-Width="100px" DataField="remarks" HeaderText="Remarks" />
</Columns>
</asp:GridView>
</asp:Panel>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField ItemStyle-Width="0px" DataField="mkey" Visible="false" HeaderText="Mkey" />
<asp:BoundField ItemStyle-Width="8%" DataField="Doc_No" HeaderText="IW/ No" />
<asp:BoundField ItemStyle-Width="10%" DataField="Doc_Date" HeaderText="IW/ Date" />
<asp:BoundField ItemStyle-Width="12%" DataField="DocType" HeaderText="Doc type" />
<asp:BoundField ItemStyle-Width="15%" DataField="Party_Name" HeaderText="Party Name" />
<asp:BoundField ItemStyle-Width="0" Visible="true" DataField="Status_Flag" HeaderText="Status" />
<asp:BoundField ItemStyle-Width="10%" DataField="LastAction_datetime" HeaderText="Last Action Date" />
<asp:BoundField ItemStyle-Width="10%" DataField="CurrStatus" HeaderText="Current Status" />
<asp:BoundField ItemStyle-Width="10%" DataField="Type_desc" HeaderText="Resp Dept" />
<asp:BoundField ItemStyle-Width="12%" DataField="UserName" HeaderText="Resp User" />
<asp:BoundField ItemStyle-Width="8%" DataField="No_Of_Days" HeaderText="No of days" />
<asp:HyperLinkField ItemStyle-Width="5%" DataNavigateUrlFields="Mkey, Status, Doc_No"
DataNavigateUrlFormatString="~/Administration/Dispatch/Inward/FrmInwardNextAction.aspx?Inward_mkey={0}&Status={0}&IWNO={0}"
HeaderText="Status" DataTextField="Status" Target="_blank" />
<asp:HyperLinkField ItemStyle-Width="5%" DataNavigateUrlFields="Mkey, Status, Doc_No"
HeaderText="View" DataTextField="View" Target="_blank" DataNavigateUrlFormatString="~/Administration/Dispatch/Inward/InwardDocDetails.aspx?Key={0}&Status={0}&IWNO={0}" />
</Columns>
</asp:GridView>
Columns like HyperLinkField and CheckBoxField behave a little differently than BoundField. They don't just simply contain text like BoundField. You have to get the control within the cell. You can get the child controls of the cell using the Controls collection. We know that specifically for a HyperLinkField, the HyperLink will be the first control in the collection.
HyperLink hyp = (HyperLink)UltraWebGrid1.Rows[IntPriI].Cells[12].Controls[0];
Can you try it like this
if (StrPriStatus == "5")
{
HyperLink HyperLinkObj = (HyperLink)UltraWebGrid1.Rows[IntPriI].Cells[12].Controls[0];
HyperLinkObj.Text = "";
}

How do I get value of field in nested gridview where checkbox is checked?

I have a nested gridview inside another gridview. The parent gridview has a list of tasks, and each task has a list of steps (the child gridview). Each step has a checkbox so once a user is done with a step, he'll check the checkbox and that will fire the CheckChanged event in which I have a stored procedure to update the database so the checked step registers as completed.
I have a CheckChanged event that looks for the step ID of the row the checked checkbox was in, then fires off the stored procedure using the step ID as an input parameter. This works. However, steps can be added, and for some reason, when a check box on an earlier step is clicked, the code that looks for the step ID won't go backwards and recognize the step ID. In other words, if a if the the step ID of a certain task is 20, and it is checked and the event fires off, if I add a step to an earlier task (a task listed higher on the gridview) and that step has an ID of 21, clicking on it will constantly register the step ID as 20, as if the CheckChanged event doesn't recognize a step added to another task. Here is my code:
aspx:
<asp:GridView ID="GridView1"
DataKeyNames="TaskID"
runat="server"
OnRowDataBound="GridView1_OnRowDataBound"
CssClass="DefaultGrid"
onRowCommand="GridView1_RowCommand"
EmptyDataText = "<br/>There are no Tasks in this Project."
AllowPaging="True"
AllowSorting="True"
CellPadding="4"
DataSourceID="SqlDataSource_mp_Display_Tasks_Home"
ForeColor="#333333"
GridLines="None"
AutoGenerateColumns="False">
<AlternatingRowStyle BackColor="White" ForeColor="#284775" />
<RowStyle CssClass=" table-responsive body-content " />
<Columns>
<asp:CommandField ShowSelectButton="False" />
<asp:TemplateField>
<ItemTemplate>
<img alt = "" style="cursor: pointer" src="Images/plus.png" />
<asp:Panel ID="pnlOrders" runat="server" Style="display:none">
<asp:GridView ID="GridView2"
runat="server"
onRowCommand="GridView2_RowCommand"
Datakeynames="TaskStepID"
CssClass="ChildGrid"
EmptyDataText="<br/>There are no Steps in this Task."
AutoGenerateColumns="false"
onselectedindexchanged="GridView2_SelectedIndexChanged">
<Columns>
<asp:BoundField DataField="TaskStepID" HeaderText="TaskStepID" Visible="true" />
<asp:BoundField DataField="TaskID" HeaderText="TaskID" Visible="false" />
<asp:BoundField DataField="TaskStepTypeID" HeaderText="TaskStepTypeID" Visible="false"/>
<asp:BoundField DataField="TaskStepPriority" HeaderText="Task Step Priority" Visible="false" />
<asp:BoundField ItemStyle-Width="70%" DataField="TaskStepDesc" HeaderText="Step Description" />
<asp:TemplateField HeaderText="Step Completed" ItemStyle-Width="15%" >
<ItemStyle HorizontalAlign="Center" />
<ItemTemplate>
<asp:Checkbox ID="TaskStepCompleted"
OnCheckedChanged="TaskStepCompleted_CheckedChanged"
Checked='<%# Eval("TaskStepCompleted") %>'
runat="server"
AutoPostBack="true" />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="TaskStepComment" HeaderText="TaskStepComment" Visible="false" />
<asp:TemplateField HeaderText="Step Activity" ItemStyle-Width="15%">
<ItemTemplate>
<asp:LinkButton Text="Add" ID="Addstep" runat="server" CommandName="addstep" CommandArgument='<%# Eval("TaskStepID") %>'/>
<asp:LinkButton Text="Edit" ID="Editstep" runat="server" CommandName="editstep" CommandArgument='<%# Eval("TaskStepID") %>'/>
<asp:LinkButton Text="Delete" ID="Deletestep" runat="server" CommandName="deletestep" OnClientClick="return confirm('<%=AlertMe%>');" CommandArgument='<%# Eval("TaskStepID") %>'/>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</asp:Panel>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="TaskID" HeaderText="Task ID" Visible="false"/>
<asp:BoundField DataField="ProjectID" HeaderText="Project ID" Visible="false" />
<asp:BoundField DataField="TaskTypeID" HeaderText="Task Type ID" Visible="false" />
<asp:BoundField DataField="TaskCompleted" HeaderText="Taske Completed?" Visible="false" />
<asp:BoundField DataField="TaskCreationDate" HeaderText="Task Creation Date" Visible="false" />
<asp:BoundField DataField="TaskSubmitterID" HeaderText="Task Submitter ID" Visible="false" />
<asp:BoundField DataField="DepartmentID" HeaderText="DepartmentID" Visible="false" />
<asp:BoundField DataField="TaskDueDateCommentType" HeaderText="Due Date Comment" Visible="false" />
<asp:BoundField DataField="TaskLastUpdatedDate" HeaderText="Task Last Updated Date" Visible="false" />
<asp:BoundField DataField="TaskLastUpdatedUserID" HeaderText="Task Last Updated UserID" Visible="false" />
<asp:BoundField DataField ="TaskSubmitterName" HeaderText="Task Submitter Name" Visible="false" />
<asp:BoundField DataField="TaskLastUpdatedUser" HeaderText="Task Last Updated User" Visible="false" />
<asp:BoundField DataField="DepartmentDesc" HeaderText="Dept" visible="false"/>
<asp:TemplateField HeaderText="Task Description">
<ItemTemplate>
<asp:Label ID="TaskDescription" runat="server" Text='<%# HighlightText(Eval("TaskDescription").ToString()) %>'></asp:Label>
</ItemTemplate>
<ItemStyle Width="40%" />
</asp:TemplateField>
<asp:TemplateField HeaderText="% Comp.">
<ItemStyle HorizontalAlign="Center" />
<ItemTemplate>
<asp:Label ID="PercentCompleted" runat="server" Text='<%# (String.IsNullOrEmpty(Eval("PercentCompleted").ToString()) ? "0" : Eval("PercentCompleted")) + " %" %>' ></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="TaskDueDate" HeaderStyle-HorizontalAlign="Right" HeaderText="Task Due Date" DataFormatString="{0:MM-dd-yyyy}" visible="true"/>
<asp:BoundField DataField="TaskTypeName" HeaderText="Task Type" visible="true" />
<asp:BoundField DataField="DepartmentAbbrev" HeaderText="Dept" Visible="true" />
<asp:TemplateField HeaderText="Activity">
<ItemTemplate>
<asp:LinkButton Text="Edit" ID="Edittask" runat="server" CommandName="edittask" CommandArgument='<%# Eval("TaskID") %>'/>
<asp:LinkButton Text="Delete" ID="Deletetask" runat="server" CommandName="deletetask" OnClientClick="return confirm('Are you sure you wish to Delete this Task?');" CommandArgument='<%# Eval("TaskID") %>'/>
<asp:LinkButton Text="Comments" ID="Detailstask" runat="server" CommandName="detailstask" CommandArgument='<%# Eval("TaskID") %>'/>
</ItemTemplate>
</asp:TemplateField>
</Columns>
<EditRowStyle BackColor="#999999" />
<FooterStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
<HeaderStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="#284775" ForeColor="White" HorizontalAlign="Center" />
<RowStyle BackColor="#F7F6F3" ForeColor="#333333" />
<SelectedRowStyle BackColor="#E2DED6" Font-Bold="True" ForeColor="#333333" />
<SortedAscendingCellStyle BackColor="#E9E7E2" />
<SortedAscendingHeaderStyle BackColor="#506C8C" />
<SortedDescendingCellStyle BackColor="#FFFDF8" />
<SortedDescendingHeaderStyle BackColor="#6F8DAE" />
</asp:GridView>
<asp:SqlDataSource ID="SqlDataSource_mp_Display_Tasks_Home" runat="server" FilterExpression="TaskDescription LIKE '%{0}%'" ConnectionString="<%$ ConnectionStrings:IntelliBaseConnectionString_mp_Display_Projects_Home %>" SelectCommand="mp_Display_Tasks_Home" SelectCommandType="StoredProcedure" ProviderName="System.Data.SqlClient">
<SelectParameters>
<asp:Parameter Name="Incoming_ProjectID" Type="Int32" />
</SelectParameters>
<FilterParameters>
<asp:ControlParameter Name="TaskDescription" ControlID="txtSearchtasks" PropertyName="Text"/>
</FilterParameters>
</asp:SqlDataSource>
cs:
protected void TaskStepCompleted_CheckedChanged(object sender, EventArgs e)
{
// this nested foreach grabs the taskstepID number for the row in which the checkbox was just checked.
foreach (GridViewRow row in GridView1.Rows)
{
if (row.RowType == DataControlRowType.DataRow)
{
GridView GridView2 = (GridView)row.FindControl("GridView2");
if (GridView2 != null)
{
foreach (GridViewRow Row in GridView2.Rows)
{
if (Row.RowType == DataControlRowType.DataRow)
{
System.Web.UI.WebControls.CheckBox chk = (System.Web.UI.WebControls.CheckBox)Row.FindControl("TaskStepCompleted");
if (chk.Checked || !chk.Checked)
{
Session["TaskStepID"] = GridView2.DataKeys[Row.RowIndex]["TaskStepID"].ToString();
}
}
}
}
}
}
// autopost back the check box to run the stored procedure
var TaskStepID = Session["TaskStepID"].ToString();
var ProjectID = Session["ProjectID"].ToString();
using (var conn = new SqlConnection("Data Source=orlandosql1;Initial Catalog=IntelliBase;Persist Security Info=True;User ID=trainingsurveys_webuser;Password=C#mb3rSQL;"))
using (SqlCommand cmd = new SqlCommand("dbo.mp_Task_Step_Completed_Toggle", conn))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("#TaskStepID", SqlDbType.Int).Value = TaskStepID;
cmd.Parameters.Add("#AdminUserID", SqlDbType.Int).Value = "10";
cmd.Parameters.Add("#LogActionItemID", SqlDbType.Int).Value = "15";
cmd.Parameters.AddWithValue("#DTStamp", SqlDbType.DateTime.ToString("d")).Value = DateTime.Now.ToString("d");
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
Response.Redirect("Tasks.aspx?id=" + ProjectID.ToString());
}
}
I tried my best to describe the issue. To recap: nested gridview has rows with check boxes. Clicking the checkbox automatically updates db tables, but regardless of check box row, the CheckedChanged code will only register the ID of the most recent ID. Any insight is appreciated.
Carlos
If I understand correctly, I believe your issue comes with how you think you are grabbing the TaskStepID of your GridViewRow. You are doing a lot of unnecessary work. Instead of iterating every row of both GridViews, just grab the GridViewRow of the CheckBox that was just clicked.
CheckBox cb = (CheckBox)sender;
GridViewRow row = (GridViewRow)cb.NamingContainer;
GridView gv = (GridView)row.NamingContainer;
string taskStepID = gv.DataKeys[row.RowIndex].Value.ToString();
Notice how by iterating each row like you were, you were always getting the TaskStepID of the last row. So when you added a row before it, it was using the last row instead of the one you expected.

Nested GridView - How to trigger the Child GridView Button Click event

I need to show a Master/Child data in a page and I have used multiple GridViews to achieve the same. So, I have created two GridViews (Parent & Child) and now I want to fire the Button click event (i.e. btnLock) from the child gridview control and do some DB operations. So, I dont know how to achieve this.
Please help.
<asp:UpdatePanel ID="pnlUpdate" runat="server">
<ContentTemplate>
<asp:GridView Width="100%" AllowPaging="True" ID="gvCustomers" AutoGenerateColumns="False"
DataSourceID="sqlDsCustomers" runat="server" ShowHeader="False" OnRowCreated="gvCustomers_RowCreated">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<div class="group" id='<%#String.Format("customer{0}",Container.DataItemIndex) %>' onclick='showhide(<%#String.Format("\"#customer{0}\"",Container.DataItemIndex) %>,<%#String.Format("\"#order{0}\"",Container.DataItemIndex) %>)'>
<asp:Image ID="imgCollapsible" CssClass="first" ImageUrl="~/Assets/img/plus.png"
Style="margin-right: 5px;" runat="server" /><span class="header">
<%#Eval("CustomerID")%>
:
<%#Eval("CompanyName")%>
(<%#Eval("TotalOrders")%>
Orders) </span>
</div>
<asp:SqlDataSource ID="sqlDsOrders" runat="server" ConnectionString="<%$ ConnectionStrings:Northwind %>"
SelectCommand="SELECT [OrderID], [OrderDate], [RequiredDate], [Freight], [ShippedDate] FROM [Orders] WHERE ([CustomerID] = #CustomerID)">
<SelectParameters>
<asp:Parameter Name="CustomerID" Type="String" DefaultValue="" />
</SelectParameters>
</asp:SqlDataSource>
<div id='<%#String.Format("order{0}",Container.DataItemIndex) %>' class="order">
<asp:GridView AutoGenerateColumns="false" CssClass="grid" ID="gvOrders" DataSourceID="sqlDsOrders"
runat="server" ShowHeader="true" EnableViewState="false">
<RowStyle CssClass="row" />
<AlternatingRowStyle CssClass="altrow" />
<Columns>
<asp:TemplateField ItemStyle-CssClass="rownum">
<ItemTemplate>
<%# Container.DataItemIndex + 1 %>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField HeaderText="Order ID" DataField="OrderID" ItemStyle-Width="80px" />
<asp:BoundField HeaderText="Date Ordered" DataField="OrderDate" DataFormatString="{0:MM/dd/yyyy}"
ItemStyle-Width="100px" />
<asp:BoundField HeaderText="Date Required" DataField="RequiredDate" DataFormatString="{0:MM/dd/yyyy}"
ItemStyle-Width="110px" />
<asp:BoundField HeaderText="Freight" DataField="Freight" DataFormatString="{0:c}"
ItemStyle-Width="50px" ItemStyle-HorizontalAlign="Right" />
<asp:BoundField HeaderText="Date Shipped" DataField="ShippedDate" DataFormatString="{0:MM/dd/yyyy}"
ItemStyle-Width="100px" />
<asp:TemplateField>
<ItemTemplate>
<asp:Button ID="btnLock" Text="Lock" CommandName="Lock" CommandArgument=<%# Eval("OrderID") %> runat="server" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</div>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</ContentTemplate>
</asp:UpdatePanel>
Thanks
Use the RowCommand:
<asp:GridView AutoGenerateColumns="false" CssClass="grid" ID="gvOrders" DataSourceID="sqlDsOrders"
runat="server" ShowHeader="true" EnableViewState="false"
onrowcommand="gvOrders_RowCommand"
>
........
</asp:GridView >
protected void gvOrders_RowCommand(Object sender, GridViewCommandEventArgs e)
{
// If multiple buttons are used in a GridView control, use the
// CommandName property to determine which button was clicked.
if(e.CommandName=="Lock")
{
// Convert the row index stored in the CommandArgument
// property to an Integer.
int index = Convert.ToInt32(e.CommandArgument);
//dowork
}
}

asp.net Gridview: buttons accessing data for each row

I'm trying to code a Gridview that has a button on each row that when clicked will expose that particular rows data for use, but I'm not sure how the data would be passed.
The Gridview:
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataKeyNames="ID"
DataSourceID="SqlDataSource2">
<Columns>
<asp:BoundField DataField="ID" HeaderText="ID" InsertVisible="False" ReadOnly="True"
SortExpression="ID" Visible="False" />
<asp:BoundField DataField="RelationID" HeaderText="RelationID" InsertVisible="False"
SortExpression="RelationID" Visible="False" />
<asp:BoundField DataField="UserRole" HeaderText="UserRole" InsertVisible="False"
SortExpression="UserRole" Visible="False" />
<asp:BoundField DataField="FirstName" HeaderText="First Name" SortExpression="FirstName" />
<asp:BoundField DataField="Surname" HeaderText="Surname" SortExpression="Surname" />
<asp:BoundField DataField="Telephone" HeaderText="Telephone" SortExpression="Telephone" />
<asp:BoundField DataField="Email" HeaderText="Email" SortExpression="Email" />
<asp:BoundField DataField="Hash" HeaderText="Hash" InsertVisible="False" SortExpression="Hash"
Visible="False" />
<asp:BoundField DataField="DateCreated" HeaderText="Date Invited" SortExpression="DateCreated" />
<asp:TemplateField HeaderText="Resend Welcome Email">
<ItemTemplate>
<asp:Button runat="server" ID="btnResend" Text="Resend" OnClick="btnResend_Click" />
</ItemTemplate>
<ItemStyle HorizontalAlign="Center" VerticalAlign="Middle" />
</asp:TemplateField>
</Columns>
</asp:GridView>
The button_OnClick
protected void btnResend_Click(object sender, EventArgs e)
{
bool boolEmailSent = Email.sendWelcomeEmail(//Email from Row, //FirstName from Row, //Surname from Row, //Hash from Row);
if (boolEmailSent == true)
{
//Confirm to User
}
else
{
//TODO: write error to log
}
}
This article covers what you're attempting in more depth than we could answer here:
http://authors.aspalliance.com/aspxtreme/webforms/controls/addingbuttonfieldstoGridView.aspx
And here's another:
http://msdn.microsoft.com/en-us/library/bb907626.aspx

Categories

Resources