I have text boxes in footer for with insert button. Called a javascript Calculate on textbox onchange() for multiplying values.
Its working fine for first two inserts. From third i am getting this error.
"Microsoft JScript runtime error: Object required"
Below is the code:
function calculate() {
var Num1 = parseFloat(document.getElementById('<%=((TextBox)gvDowntime.FooterRow.FindControl("txtAddImpactedNoEmployee")).ClientID %>').value);
var Num2 = parseInt(document.getElementById('<%=((TextBox)gvDowntime.FooterRow.FindControl("txtAddDowntimePerEmployee")).ClientID %>').value);
var Num3 = Num1 * Num2;
if (!isNaN(Num3)) {
document.getElementById('<%=((TextBox)gvDowntime.FooterRow.FindControl("txtAddTotalDowntimeImpact")).ClientID %>').value = Num3;
}
}
<asp:GridView ID="gvDowntime" runat="server" AutoGenerateColumns="False" ShowHeaderWhenEmpty="True"
EnableModelValidation="True" ShowFooter="True" Width="100%"
CellPadding="4" ForeColor="#333333" GridLines="None"
onrowdatabound="gvDowntime_RowDataBound"
onrowcommand="gvDowntime_RowCommand">
<AlternatingRowStyle BackColor="White" ForeColor="#284775" />
<Columns>
<asp:TemplateField HeaderText="Downtime" FooterStyle-HorizontalAlign="Center" ItemStyle-HorizontalAlign="Center">
<ItemTemplate>
<asp:Label ID="lblEntryID" runat="server" Visible="false"></asp:Label>
<asp:Label ID="lblDowntime" runat="server"></asp:Label>
</ItemTemplate>
<FooterTemplate>
<asp:DropDownList ID="ddlAddDowntime" runat="server"></asp:DropDownList>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="StartTime" FooterStyle-HorizontalAlign="Center" ItemStyle-HorizontalAlign="Center">
<ItemTemplate>
<asp:Label ID="lblStartTime" runat="server"></asp:Label>
</ItemTemplate>
<FooterTemplate>
<asp:DropDownList ID="ddlAddStartTime" runat="server"></asp:DropDownList>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="EndTime" FooterStyle-HorizontalAlign="Center" ItemStyle-HorizontalAlign="Center">
<ItemTemplate>
<asp:Label ID="lblEndTime" runat="server"></asp:Label>
</ItemTemplate>
<FooterTemplate>
<asp:DropDownList ID="ddlAddEndTime" runat="server"></asp:DropDownList>
<asp:Label ID="lblAddTimeValidation" runat="server" ForeColor="Red"></asp:Label>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Impacted # of<BR>Employees" FooterStyle-HorizontalAlign="Center" ItemStyle-HorizontalAlign="Center">
<ItemTemplate>
<asp:Label ID="lblImpactedNoEmployee" runat="server"></asp:Label>
</ItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtAddImpactedNoEmployee" runat="server" Width="100px" Font-Size="Smaller" onchange="calculate();"></asp:TextBox>
<asp:RequiredFieldValidator ID="reqImpact" runat="server" Display="Dynamic" Text="*"
ControlToValidate="txtAddImpactedNoEmployee" ValidationGroup="NewEntry" ForeColor="Red"></asp:RequiredFieldValidator>
<asp:RegularExpressionValidator runat="server" id="rexNumber" controltovalidate="txtAddImpactedNoEmployee" ValidationGroup="NewEntry"
validationexpression="[0-9]+(\.[0-9][0-9]?)?" errormessage="<BR>Please enter number!" ForeColor="Red" Display="Dynamic"/>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Downtime per<BR>Employee(Mins)" FooterStyle-HorizontalAlign="Center" ItemStyle-HorizontalAlign="Center">
<ItemTemplate>
<asp:Label ID="lblDowntimePerEmployee" runat="server"></asp:Label>
</ItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtAddDowntimePerEmployee" runat="server" Width="100px" Font-Size="Smaller" onchange="calculate();"></asp:TextBox>
<asp:RequiredFieldValidator ID="req" runat="server" Display="Dynamic" Text="*"
ControlToValidate="txtAddDowntimePerEmployee" ValidationGroup="NewEntry" ForeColor="Red"></asp:RequiredFieldValidator>
<asp:RegularExpressionValidator runat="server" id="rex" controltovalidate="txtAddDowntimePerEmployee" ValidationGroup="NewEntry"
validationexpression="^[0-9]+$" errormessage="<BR>Please enter number!" ForeColor="Red" Display="Dynamic"/>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Total Downtime<BR>Impact(Mins)" FooterStyle-HorizontalAlign="Center" ItemStyle-HorizontalAlign="Center">
<ItemTemplate>
<asp:Label ID="lblTotalDowntimeImpact" runat="server"></asp:Label>
</ItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtAddTotalDowntimeImpact" runat="server" Width="100px" Font-Size="Smaller" ReadOnly="true"></asp:TextBox>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Production Units" FooterStyle-HorizontalAlign="Center" ItemStyle-HorizontalAlign="Center">
<ItemTemplate>
<asp:Label ID="lblProductionUnits" runat="server" ></asp:Label>
</ItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtAddProductionUnits" Width="100px" Font-Size="Smaller" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator ID="reqDowntime" runat="server" Display="Dynamic" Text="*"
ControlToValidate="txtAddProductionUnits" ValidationGroup="NewEntry" ForeColor="Red"></asp:RequiredFieldValidator>
<asp:RegularExpressionValidator runat="server" id="rexProdUnit" controltovalidate="txtAddProductionUnits" ValidationGroup="NewEntry"
validationexpression="^[0-9]+$" errormessage="<BR>Please enter number!" ForeColor="Red" Display="Dynamic"/>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField FooterStyle-HorizontalAlign="Center" ItemStyle-HorizontalAlign="Center">
<ItemTemplate>
<asp:LinkButton ID="btnDelete" runat="server" CommandName="DEL">Delete</asp:LinkButton>
</ItemTemplate>
<FooterTemplate>
<asp:Button ID="btnInsert" runat="server" Text="Insert" ValidationGroup='NewEntry' CausesValidation='true' CommandName="insert" />
</FooterTemplate>
</asp:TemplateField>
</Columns>
<EditRowStyle BackColor="#999999" />
<FooterStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
<HeaderStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" CssClass="gradientDemo" Height="35px"/>
<PagerStyle BackColor="#284775" ForeColor="White" HorizontalAlign="Center" />
<RowStyle BackColor="#F7F6F3" ForeColor="#333333" />
<SelectedRowStyle BackColor="#E2DED6" Font-Bold="True" ForeColor="#333333" />
protected void gvDowntime_RowCommand(object sender, GridViewCommandEventArgs e)
{
try
{
if (e.CommandName == "insert")
{
GridViewRow gvr = (GridViewRow)(((Button)e.CommandSource).NamingContainer);
DropDownList ddlAddDowntime = (DropDownList)gvr.FindControl("ddlAddDowntime");
DropDownList ddlAddStartTime = (DropDownList)gvr.FindControl("ddlAddStartTime");
DropDownList ddlAddEndTime = (DropDownList)gvr.FindControl("ddlAddEndTime");
TextBox txtAddImpactedNoEmployee = (TextBox)gvr.FindControl("txtAddImpactedNoEmployee");
TextBox txtAddDowntimePerEmployee = (TextBox)gvr.FindControl("txtAddDowntimePerEmployee");
TextBox txtAddTotalDowntimeImpact = (TextBox)gvr.FindControl("txtAddTotalDowntimeImpact");
TextBox txtAddProductionUnits = (TextBox)gvr.FindControl("txtAddProductionUnits");
Label lblAddTimeValidation = (Label)gvr.FindControl("lblAddTimeValidation");
txtAddTotalDowntimeImpact.Text = Request.Form[txtAddTotalDowntimeImpact.UniqueID];
DowntimeEntry objEntry = new DowntimeEntry();
if (!BLL.DowntimeEntryDetail.isValidTimes(ddlAddStartTime.SelectedItem.Text, ddlAddEndTime.SelectedItem.Text))
{
lblAddTimeValidation.Text = "EndTime should be greater!";
return;
}
objEntry.Downtime = ddlAddDowntime.SelectedItem.Text;
objEntry.StartTime = ddlAddStartTime.SelectedItem.Text;
objEntry.EndTime = ddlAddEndTime.SelectedItem.Text;
objEntry.ImpactedNoEmployees = Convert.ToDouble(txtAddImpactedNoEmployee.Text);
objEntry.DowntimePerEmployee = Convert.ToInt32(txtAddDowntimePerEmployee.Text);
objEntry.TotalDowntimeImpact = Convert.ToDouble(txtAddTotalDowntimeImpact.Text);
objEntry.ProductionUnit = Convert.ToInt32(txtAddProductionUnits.Text);
objEntry.ResolutionAction = "";
objEntry.ResolutionOwner = "";
objEntry.RequestID = Convert.ToInt32(Request.QueryString["ReqID"]);
BLL.DowntimeEntryDetail.UpdateDowntimeEntryRecord(objEntry);
loadDowntimeEntry();
}
}
catch (Exception ex)
{
BLL.DowntimeSummaryDetail.AddException(ex);
}
}
public void loadDowntimeEntry()
{
try
{
bool blResolutionvisiblity = true;
listDowntimeEntry = BLL.DowntimeEntryDetail.LoadDowntimeEntryDetail(Convert.ToInt32(Request.QueryString["ReqID"]));
gvDowntime.DataSource = listDowntimeEntry;
gvDowntime.DataBind();
//if (listDowntimeEntry.FindAll(x => x.ResolutionAction == "" || x.ResolutionAction == null).Count > 0 && blResolutionvisiblity)
// lblHeader.Text = "Reporting & Resolution Pending";
//else
lblHeader.Text = "Reporting & Resolution";
if (blResolutionvisiblity)
{
gvResolution.DataSource = listDowntimeEntry;
gvResolution.DataBind();
}
//else
// panelHeader.Visible = false;
}
catch (Exception ex)
{
BLL.DowntimeSummaryDetail.AddException(ex);
}
}
protected void gvDowntime_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
DowntimeEntry objEntry = (DowntimeEntry)e.Row.DataItem;
if (objEntry.Downtime == null)
{
e.Row.Visible = false;
}
else
{
Label lblDowntime = (Label)e.Row.FindControl("lblDowntime");
Label lblStartTime = (Label)e.Row.FindControl("lblStartTime");
Label lblEndTime = (Label)e.Row.FindControl("lblEndTime");
Label lblImpactedNoEmployee = (Label)e.Row.FindControl("lblImpactedNoEmployee");
Label lblDowntimePerEmployee = (Label)e.Row.FindControl("lblDowntimePerEmployee");
Label lblTotalDowntimeImpact = (Label)e.Row.FindControl("lblTotalDowntimeImpact");
Label lblProductionUnits = (Label)e.Row.FindControl("lblProductionUnits");
Label lblEntryID = (Label)e.Row.FindControl("lblEntryID");
lblEntryID.Text = Convert.ToString(objEntry.EntryID);
lblDowntime.Text = objEntry.Downtime;
lblStartTime.Text = objEntry.StartTime;
lblEndTime.Text = objEntry.EndTime;
lblImpactedNoEmployee.Text = Convert.ToString(objEntry.ImpactedNoEmployees);
lblDowntimePerEmployee.Text = Convert.ToString(objEntry.DowntimePerEmployee);
lblTotalDowntimeImpact.Text = Convert.ToString(objEntry.TotalDowntimeImpact);
lblProductionUnits.Text = Convert.ToString(objEntry.ProductionUnit);
}
}
else if (e.Row.RowType == DataControlRowType.Footer)
{
DropDownList ddlAddDowntime = (DropDownList)e.Row.FindControl("ddlAddDowntime");
DropDownList ddlAddStartTime = (DropDownList)e.Row.FindControl("ddlAddStartTime");
DropDownList ddlAddEndTime = (DropDownList)e.Row.FindControl("ddlAddEndTime");
TextBox txtAddImpactedNoEmployee = (TextBox)e.Row.FindControl("txtAddImpactedNoEmployee");
TextBox txtAddDowntimePerEmployee = (TextBox)e.Row.FindControl("txtAddDowntimePerEmployee");
TextBox txtAddTotalDowntimeImpact = (TextBox)e.Row.FindControl("txtAddTotalDowntimeImpact");
TextBox txtAddProductionUnits = (TextBox)e.Row.FindControl("txtAddProductionUnits");
List<DownTime> listDowntime = BLL.DowntimeDetail.LoadDowntimeDetail(true);
foreach (DownTime objDowntime in listDowntime)
{
ListItem itmDowntime = new ListItem(objDowntime.DowntimeName, Convert.ToString(objDowntime.ID));
itmDowntime.Attributes.Add("Title", objDowntime.Desc);
ddlAddDowntime.Items.Add(itmDowntime);
}
List<TimeHour> listTime = BLL.TimeHourDetail.LoadTimeHourDetail(true);
foreach (TimeHour objTime in listTime)
{
ddlAddStartTime.Items.Add(new ListItem(objTime.TimeHours, Convert.ToString(objTime.ID)));
ddlAddEndTime.Items.Add(new ListItem(objTime.TimeHours, Convert.ToString(objTime.ID)));
}
}
}
Related
While binding the gridview i want to get cell control value but in my code throwing an error.Like below i am binding the gridview with edit,delete,and footer rows.
<asp:GridView ID="GridView1" runat="server" Width = "100%"
OnDataBound = "OnDataBound" OnRowCreated = "OnRowCreated"
AutoGenerateColumns = "False" Font-Names = "Arial"
Font-Size = "11pt" AlternatingRowStyle-BackColor = "#C2D69B"
HeaderStyle-BackColor = "green" AllowSorting="True" AllowPaging ="True" ShowFooter = "True"
OnPageIndexChanging = "OnPaging" onrowediting="EditCustomer"
onrowupdating="UpdateCustomer" onrowcancelingedit="CancelEdit" PageSize = "30">
<Columns>
<asp:TemplateField ItemStyle-Width = "100px" HeaderText="S.NO">
<ItemTemplate><%#Container.DataItemIndex + 1%>
</ItemTemplate>
<ItemStyle Width="100px" />
</asp:TemplateField>
<asp:TemplateField ItemStyle-Width = "100px" HeaderText = "Item Code">
<FooterTemplate>
<asp:Label ID="lblAddItemCode" runat="server"
Text='<%# Eval("ItemId")%>'></asp:Label>
</FooterTemplate>
<ItemTemplate>
<asp:Label ID="lblViewItemCode" runat="server"
Text='<%# Eval("ItemId")%>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:Label ID="lblEditItemCode" runat="server"
Text='<%# Eval("ItemId")%>'></asp:Label>
</EditItemTemplate>
<ItemStyle Width="100px" />
</asp:TemplateField>
<asp:TemplateField ItemStyle-Width = "100px" HeaderText = "Item Name">
<EditItemTemplate>
<asp:Label ID="lblEditItemName" runat="server"
Text='<%# Eval("ItemName")%>'></asp:Label>
</EditItemTemplate>
<FooterTemplate>
<asp:DropDownList ID="ddlItemNameGrid" runat="server"
DataSourceID="SqlDataSource1" DataTextField="ItemName"
DataValueField="ItemId">
</asp:DropDownList>
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:crmConnectionString3 %>"
SelectCommand="SELECT [ItemId], [ItemName] FROM [ItemMaster] WHERE ([Company_Id] = #Company_Id)">
<SelectParameters>
<asp:SessionParameter DefaultValue="1014" Name="Company_Id"
SessionField="RegistrationId" Type="Int32" />
</SelectParameters>
</asp:SqlDataSource>
</FooterTemplate>
<ItemTemplate>
<asp:Label ID="lblViewItemName" runat="server"
Text='<%# Eval("ItemName")%>'></asp:Label>
</ItemTemplate>
<ItemStyle Width="100px" />
</asp:TemplateField>
<asp:TemplateField ItemStyle-Width = "150px" HeaderText = "Unit">
<ItemTemplate>
<asp:Label ID="lblViewUnit" runat="server"
Text='<%# Eval("Unit")%>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtEditUnit" runat="server" Text='<%# Eval("Unit")%>' ValidationGroup="EditValidations"></asp:TextBox>
<asp:RequiredFieldValidator ID="reqtxtEditUnit" CssClass="Validators" Display="Dynamic" ControlToValidate="txtEditUnit" runat="server"
ErrorMessage="Unit is required." ForeColor="Red" ValidationGroup="EditValidations"></asp:RequiredFieldValidator>
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtAddUnit" runat="server" ValidationGroup="AddValidations"></asp:TextBox>
<asp:RequiredFieldValidator ID="reqtxtAddUnit" CssClass="Validators" Display="Dynamic" ControlToValidate="txtAddUnit" runat="server"
ErrorMessage="Unit is required." ForeColor="Red" ValidationGroup="AddValidations"></asp:RequiredFieldValidator>
</FooterTemplate>
<ItemStyle Width="150px" />
</asp:TemplateField>
<asp:TemplateField ItemStyle-Width = "150px" HeaderText = "Quantity">
<ItemTemplate>
<asp:Label ID="lblViewQuantity" runat="server"
Text='<%# Eval("Quantity")%>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtEditQuantity" runat="server"
Text='<%# Eval("Quantity")%>'></asp:TextBox>
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtAddQuantity" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator ID="reqtxtAddQuantity" CssClass="Validators" Display="Dynamic" ControlToValidate="txtAddQuantity" runat="server"
ErrorMessage="Quantity is required." ForeColor="Red" ValidationGroup="AddValidations"></asp:RequiredFieldValidator>
</FooterTemplate>
<ItemStyle Width="150px" />
</asp:TemplateField>
<asp:TemplateField ItemStyle-Width = "150px" HeaderText = "Rate">
<ItemTemplate>
<asp:Label ID="lblViewRate" runat="server"
Text='<%# Eval("Rate")%>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtEditRate" runat="server" Text='<%# Eval("Rate")%>'></asp:TextBox>
<asp:RequiredFieldValidator ID="reqtxtEditRate" CssClass="Validators" Display="Dynamic" ControlToValidate="txtEditRate" runat="server"
ErrorMessage="Quantity is required." ForeColor="Red" ValidationGroup="EditValidations"></asp:RequiredFieldValidator>
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtAddRate" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator ID="reqtxtAddRate" CssClass="Validators" Display="Dynamic" ControlToValidate="txtAddRate" runat="server"
ErrorMessage="Rate is required." ForeColor="Red" ValidationGroup="AddValidations"></asp:RequiredFieldValidator>
</FooterTemplate>
<ItemStyle Width="150px" />
</asp:TemplateField>
<asp:TemplateField ItemStyle-Width = "150px" HeaderText = "Total">
<ItemTemplate>
<asp:Label ID="lblViewTotal" runat="server"
Text='<%# Eval("Total")%>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtEditTotal" runat="server" Text='<%# Eval("Total")%>'></asp:TextBox>
<asp:RequiredFieldValidator ID="reqtxtEditTotal" CssClass="Validators" Display="Dynamic" ControlToValidate="txtEditTotal" runat="server"
ErrorMessage="Total is required." ForeColor="Red" ValidationGroup="EditValidations"></asp:RequiredFieldValidator>
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtAddTotal" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator ID="reqtxtAddTotal" CssClass="Validators" Display="Dynamic" ControlToValidate="txtAddTotal" runat="server"
ErrorMessage="Total is required." ForeColor="Red" ValidationGroup="AddValidations"></asp:RequiredFieldValidator>
</FooterTemplate>
<ItemStyle Width="150px" />
</asp:TemplateField>
<asp:TemplateField ItemStyle-Width="80px" HeaderText="Add Item">
<ItemTemplate>
<%--<span onclick="return confirm('Are you sure to Delete the record?')">
<asp:LinkButton ID="lnkB" runat="Server" Text="Delete" CommandName="ItemDelete"></asp:LinkButton>
</span>--%>
<%--<asp:LinkButton ID="lnkRemove" runat="server" OnClick="lnkRemove_Click">Delete</asp:LinkButton>--%>
<asp:LinkButton ID="lnkRemove" runat="server"
CommandArgument='<%#Eval("ItemDetailId")%>' Text="Delete" OnClientClick = "return confirm('Do you want to delete?')"
onclick="DeleteRecord"></asp:LinkButton>
</ItemTemplate>
<FooterTemplate>
<asp:Button ID="btnAdd" runat="server" Text="Add" ValidationGroup="AddValidations"
OnClick = "InsertItemDetails" />
</FooterTemplate>
<ItemStyle Width="80px" />
</asp:TemplateField>
<%--<asp:CommandField ShowDeleteButton="True" ButtonType="Button" HeaderText="Delete Item" />--%>
<asp:CommandField ShowEditButton="True" ValidationGroup="EditValidations" HeaderText="Edit Item" />
</Columns>
</asp:GridView>
below i am retrieving 'Total' coloumn's label control value.
protected void OnRowCreated(object sender, GridViewRowEventArgs e)
{
subTotal = 0;
if (e.Row.RowType == DataControlRowType.DataRow)
{
DataTable dt = (e.Row.DataItem as DataRowView).DataView.Table;
int itemId = Convert.ToInt32(dt.Rows[e.Row.RowIndex]["ItemId"]);
total += Convert.ToDouble(dt.Rows[e.Row.RowIndex]["Total"]);
if (itemId != currentId)
{
if (e.Row.RowIndex > 0)
{
for (int i = subTotalRowIndex; i < e.Row.RowIndex; i++)
{
Label lblViewTotal = ((Label)e.Row.Cells[6].FindControl("lblViewTotal")) as Label;
if (lblViewTotal != null && lblViewTotal.Text != string.Empty) //Check whether it is null or not
{
subTotal += Convert.ToDouble(lblViewTotal.Text);
}
}
this.AddTotalRow("Sub Total", subTotal.ToString("N7"));
subTotalRowIndex = e.Row.RowIndex;
}
currentId = itemId;
}
}
}
I've modified you code little bit by handling null conditions. Please have a look.
protected void OnRowCreated(object sender, GridViewRowEventArgs e)
{
subTotal = 0;
if (e.Row.RowType == DataControlRowType.DataRow)
{
DataTable dt = (e.Row.DataItem as DataRowView).DataView.Table;
int itemId = Convert.ToInt32(dt.Rows[e.Row.RowIndex]["ItemId"]);
total += Convert.ToDecimal(dt.Rows[e.Row.RowIndex]["Total"]);
if (itemId != currentId)
{
if (e.Row.RowIndex > 0)
{
for (int i = subTotalRowIndex; i < e.Row.RowIndex; i++)
{
Label lblViewTotal = (Label)e.Row.FindControl("lblViewTotal");//First Get label
if (lblViewTotal != null && lblViewTotal.Text != string.Empty) //Check whether it is null or not
{
subTotal += Convert.ToDecimal(lblViewTotal.Text);
}
}
this.AddTotalRow("Sub Total", subTotal.ToString("N7"));
subTotalRowIndex = e.Row.RowIndex;
}
currentId = itemId;
}
}
}
Are you sure that OnRowCreated Triggers after OnDataBound ?
It may be that there is no value at the stage when you are doing the sub total.
Try using the RowDataBound event instead?
(Been a while since I did web forms work, so this is from memory, apologies if I am incorrect)
In my Asp.net App, i have a GridView and i generate the data of column[6] by myself using code behind.
by looking at the code below, i have a footer for my gridview. and the problem is my text for column[6] won't appear if i use footer.
If i delete the footertext code, then my text for column[6] is appear. what is the problem? both of the code cant use togather? i already set ShowFooter="True"
protected void Page_Load(object sender, EventArgs e)
{
for (int i = 0; i < (this.GridView1.Rows.Count); i++)
{
this.GridView1.Rows[i].Cells[6].Text = "testing";
//GridView1.Columns[1].FooterText ="footer 1";
}
}
.aspx
<asp:GridView ID="GridView1" runat="server" DataSourceID="SqlDataSource1"
AutoGenerateColumns="False" DataKeyNames="ID" CellPadding="4"
ForeColor="#333333" GridLines="None" ShowFooter="True"
onrowdatabound="GridView1_RowDataBound">
<RowStyle BackColor="#EFF3FB" />
<Columns>
<asp:BoundField DataField="reportDate" HeaderText="Report Date" dataformatstring="{0:dd MMMM yyyy}" SortExpression="reportDate" />
<asp:BoundField DataField="sponsorBonus" HeaderText="Sponsor Bonus" dataformatstring="{0:0.00}" SortExpression="sponsorBonus" HtmlEncode="False" />
<asp:BoundField DataField="pairingBonus" HeaderText="Pairing Bonus" HtmlEncode="False" SortExpression="pairingBonus" dataformatstring="{0:c}" />
<asp:BoundField DataField="staticBonus" HeaderText="Static Bonus" SortExpression="staticBonus" />
<asp:BoundField DataField="leftBonus" HeaderText="Left Bonus" SortExpression="leftBonus" />
<asp:BoundField DataField="rightBonus" HeaderText="Right Bonus" SortExpression="rightBonus" />
<asp:BoundField HeaderText="Total" SortExpression="total" >
<ItemStyle Width="100px" />
</asp:BoundField>
</Columns>
<FooterStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="#2461BF" ForeColor="White" HorizontalAlign="Center" />
<SelectedRowStyle BackColor="#D1DDF1" Font-Bold="True" ForeColor="#333333" />
<HeaderStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
<EditRowStyle BackColor="#2461BF" />
<AlternatingRowStyle BackColor="White" />
</asp:GridView>
Sample Code: To set Footer text programatically
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.Footer)
{
Label lbl = (Label)e.Row.FindControl("lblTotal");
lbl.Text = grdTotal.ToString("c");
}
}
UPDATED CODE:
decimal sumFooterValue = 0;
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
string sponsorBonus = ((Label)e.Row.FindControl("Label2")).Text;
string pairingBonus = ((Label)e.Row.FindControl("Label3")).Text;
string staticBonus = ((Label)e.Row.FindControl("Label4")).Text;
string leftBonus = ((Label)e.Row.FindControl("Label5")).Text;
string rightBonus = ((Label)e.Row.FindControl("Label6")).Text;
decimal totalvalue = Convert.ToDecimal(sponsorBonus) + Convert.ToDecimal(pairingBonus) + Convert.ToDecimal(staticBonus) + Convert.ToDecimal(leftBonus) + Convert.ToDecimal(rightBonus);
e.Row.Cells[6].Text = totalvalue.ToString();
sumFooterValue += totalvalue;
}
if (e.Row.RowType == DataControlRowType.Footer)
{
Label lbl = (Label)e.Row.FindControl("lblTotal");
lbl.Text = sumFooterValue.ToString();
}
}
In .aspx Page
<asp:GridView ID="GridView1" runat="server" DataSourceID="SqlDataSource1"
AutoGenerateColumns="False" DataKeyNames="ID" CellPadding="4"
ForeColor="#333333" GridLines="None" ShowFooter="True"
onrowdatabound="GridView1_RowDataBound">
<RowStyle BackColor="#EFF3FB" />
<Columns>
<asp:TemplateField HeaderText="Report Date" SortExpression="reportDate">
<EditItemTemplate>
<asp:TextBox ID="TextBox1" runat="server" Text='<%# Bind("reportDate") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label1" runat="server"
Text='<%# Bind("reportDate", "{0:dd MMMM yyyy}") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Sponsor Bonus" SortExpression="sponsorBonus">
<EditItemTemplate>
<asp:TextBox ID="TextBox2" runat="server" Text='<%# Bind("sponsorBonus") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label2" runat="server"
Text='<%# Bind("sponsorBonus", "{0:0.00}") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Pairing Bonus" SortExpression="pairingBonus">
<EditItemTemplate>
<asp:TextBox ID="TextBox3" runat="server" Text='<%# Bind("pairingBonus") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label3" runat="server"
Text='<%# Bind("pairingBonus", "{0:c}") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Static Bonus" SortExpression="staticBonus">
<EditItemTemplate>
<asp:TextBox ID="TextBox4" runat="server" Text='<%# Bind("staticBonus") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label4" runat="server" Text='<%# Bind("staticBonus") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Left Bonus" SortExpression="leftBonus">
<EditItemTemplate>
<asp:TextBox ID="TextBox5" runat="server" Text='<%# Bind("leftBonus") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label5" runat="server" Text='<%# Bind("leftBonus") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Right Bonus" SortExpression="rightBonus">
<EditItemTemplate>
<asp:TextBox ID="TextBox6" runat="server" Text='<%# Bind("rightBonus") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label6" runat="server" Text='<%# Bind("rightBonus") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Total" SortExpression="total">
<EditItemTemplate>
<asp:TextBox ID="TextBox7" runat="server"></asp:TextBox>
</EditItemTemplate>
<FooterTemplate>
<asp:Label ID="lbltotal" runat="server" Text="Label"></asp:Label>
</FooterTemplate>
<ItemTemplate>
<asp:Label ID="Label7" runat="server"></asp:Label>
</ItemTemplate>
<ItemStyle Width="100px" />
</asp:TemplateField>
</Columns>
<FooterStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="#2461BF" ForeColor="White" HorizontalAlign="Center" />
<SelectedRowStyle BackColor="#D1DDF1" Font-Bold="True" ForeColor="#333333" />
<HeaderStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
<EditRowStyle BackColor="#2461BF" />
<AlternatingRowStyle BackColor="White" />
</asp:GridView>
protected void gvBill_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
Total += Convert.ToDecimal(DataBinder.Eval(e.Row.DataItem, "InvMstAmount"));
else if (e.Row.RowType == DataControlRowType.Footer)
e.Row.Cells[7].Text = String.Format("{0:0}", "<b>" + Total + "</b>");
}
This can be achieved through LINQ with grouping, here a list of items pointed as a data source to the actual grid view.
Sample pseudo code which could help coding the actual.
var tabelDetails =(from li in dc.My_table
join m in dc.Table_One on li.ID equals m.ID
join c in dc.Table_two on li.OtherID equals c.ID
where //Condition
group new { m, li, c } by new
{
m.ID,
m.Name
} into g
select new
{
g.Key.ID,
Name = g.Key.FullName,
sponsorBonus= g.Where(s => s.c.Name == "sponsorBonus").Count(),
pairingBonus = g.Where(s => s.c.Name == "pairingBonus").Count(),
staticBonus = g.Where(s => s.c.Name == "staticBonus").Count(),
leftBonus = g.Where(s => s.c.Name == "leftBonus").Count(),
rightBonus = g.Where(s => s.c.Name == "rightBonus").Count(),
Total = g.Count() //Row wise Total
}).OrderBy(t => t.Name).ToList();
tabelDetails.Insert(tabelDetails.Count(), new //This data will be the last row of the grid
{
Name = "Total", //Column wise total
sponsorBonus = tabelDetails.Sum(s => s.sponsorBonus),
pairingBonus = tabelDetails.Sum(s => s.pairingBonus),
staticBonus = tabelDetails.Sum(s => s.staticBonus),
leftBonus = tabelDetails.Sum(s => s.leftBonus),
rightBonus = tabelDetails.Sum(s => s.rightBonus ),
Total = tabelDetails.Sum(s => s.Total)
});
<asp:TemplateField HeaderText="ExEmp" HeaderStyle-HorizontalAlign="Center" ItemStyle-HorizontalAlign="Center"
FooterStyle-BackColor="BurlyWood" FooterStyle-HorizontalAlign="Center">
<ItemTemplate>
<asp:TextBox ID="txtNoOfExEmp" runat="server" CssClass="form-control input-sm m-bot15"
Font-Bold="true" onkeypress="return isNumberKey(event)" Text='<%#Bind("ExEmp") %>'></asp:TextBox>
</ItemTemplate>
<HeaderStyle HorizontalAlign="Center"></HeaderStyle>
<ItemStyle HorizontalAlign="Center" Width="50px" />
<FooterTemplate>
<asp:Label ID="lblTotNoOfExEmp" Font-Bold="true" runat="server" Text="0" CssClass="form-label"></asp:Label>
</FooterTemplate>
</asp:TemplateField>
private void TotalExEmpOFMonth()
{
Label lbl_TotNoOfExEmp = (Label)GrdPFRecord.FooterRow.FindControl("lblTotNoOfExEmp");
/*Sum of the Total Amount Of month*/
foreach (GridViewRow gvr in GrdPFRecord.Rows)
{
TextBox txt_NoOfExEmp = (TextBox)gvr.FindControl("txtNoOfExEmp");
lbl_TotNoOfExEmp.Text = (Convert.ToDouble(txt_NoOfExEmp.Text) + Convert.ToDouble(lbl_TotNoOfExEmp.Text)).ToString();
lbl_TotNoOfExEmp.Text = string.Format("{0:F0}", Decimal.Parse(lbl_TotNoOfExEmp.Text));
}
}
int total = 0;
protected void gvEmp_RowDataBound(object sender, GridViewRowEventArgs e)
{
if(e.Row.RowType==DataControlRowType.DataRow)
{
total += Convert.ToInt32(DataBinder.Eval(e.Row.DataItem, "Amount"));
}
if(e.Row.RowType==DataControlRowType.Footer)
{
Label lblamount = (Label)e.Row.FindControl("lblTotal");
lblamount.Text = total.ToString();
}
}
/*This code will use gridview sum inside data list*/
SumOFdata(grd_DataDetail);
private void SumOFEPFWages(GridView grd)
{
Label lbl_TotAmt = (Label)grd.FooterRow.FindControl("lblTotGrossW");
/*Sum of the total Amount of the day*/
foreach (GridViewRow gvr in grd.Rows)
{
Label lbl_Amount = (Label)gvr.FindControl("lblGrossS");
lbl_TotAmt.Text = (Convert.ToDouble(lbl_Amount.Text) + Convert.ToDouble(lbl_TotAmt.Text)).ToString();
}
}
Here is my code where it's giving the value of ddl = null:
//event handler to bind the data to the row before rendering the gridview
protected void gridview1_RowDataBound(object sender ,GridViewRowEventArgs e)
{
if ((e.Row.RowType == DataControlRowType.DataRow)&&(e.Row.DataItem!=null))
{
//DropDownList ddlNo = (DropDownList)e.Row.FindControl("ddlNo");
DropDownList ddlNo = (DropDownList)e.Row.FindControl("ddlNo");
if (ddlNo != null)
{
ddlNo.DataSource = Test.GetData();
ddlNo.DataBind();
ddlNo.SelectedValue = gridview1.DataKeys[e.Row.RowIndex].Values[0].ToString();//datakeys are used to retain the value of the no. in edit mode
}
}
}
Here is my aspx code:
<asp:GridView ID="gridview1" runat="server" AutoGenerateColumns="false" AutoGenerateDeleteButton="false" AutoGenerateEditButton="false" ShowFooter="true" EmptyDataText="No data available." PagerStyle-HorizontalAlign="Right" AllowPaging="true" AllowSorting="true" GridLines="Vertical" Width="98%" EnableViewState="true" OnRowCancelingEdit="gridview1_RowCancelingEdit" OnRowDataBound="gridview1_RowDataBound" OnRowEditing="gridview1_RowEditing" OnRowUpdating="gridview1_RowUpdating" OnRowCommand="gridview1_RowCommand" OnRowDeleting="gridview1_RowDeleting" DataKeyNames="testID">
<Columns>
<asp:TemplateField HeaderText="Select" HeaderStyle-HorizontalAlign="Left">
<ItemTemplate>
<asp:Label ID="lblSelect" runat="server" Text="Select"></asp:Label>
<%-- <asp:CheckBox ID="chkSelect" runat="server" AutoPostBack="true" OnCheckedChanged="chkSelect_CheckChanged" />--%>
</ItemTemplate>
<HeaderStyle HorizontalAlign="Left" />
</asp:TemplateField>
<asp:BoundField DataField="testID" HeaderText="SearchId" />
<asp:TemplateField HeaderText="Name" HeaderStyle-HorizontalAlign="Left">
<EditItemTemplate>
<asp:TextBox ID="txtName" runat="server" Text='<%#Eval("testDesc") %>' />
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtNewName" runat="server"></asp:TextBox>
</FooterTemplate>
<ItemTemplate>
<asp:Label ID="lblName" runat="server" Text='<%# Bind("testDesc") %>'></asp:Label>
</ItemTemplate>
<HeaderStyle HorizontalAlign="Left" />
</asp:TemplateField>
<asp:TemplateField HeaderText="No." HeaderStyle-HorizontalAlign="Left">
<EditItemTemplate>
<asp:DropDownList ID="ddlNo" runat="server" DataTextField="testNo" DataValueField="testNo" />
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="lblNo" runat="server" Text='<%# Bind("testNo") %>'></asp:Label>
</ItemTemplate>
<FooterTemplate>
<asp:DropDownList ID="ddlNewNo" runat="server" DataTextField="testNo" DataValueField="testNo">
</asp:DropDownList>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Edit" ShowHeader="False">
<EditItemTemplate>
<asp:LinkButton ID="linkbt1" runat="server" CausesValidation="true" CommandName="Update" Text="Update">
</asp:LinkButton>
<asp:LinkButton ID="linkbt2" runat="server" CausesValidation="false" CommandName="Cancel" Text="Cancel"></asp:LinkButton>
</EditItemTemplate>
<ItemTemplate>
<asp:LinkButton ID="linkbt1" runat="server" CausesValidation="false" CommandName="Edit" Text="Edit">
</asp:LinkButton>
</ItemTemplate>
<FooterTemplate>
<asp:LinkButton ID="linkbt2" runat="server" CausesValidation="false" CommandName="AddNew" Text="AddNew">
</asp:LinkButton>
</FooterTemplate>
</asp:TemplateField>
<asp:CommandField HeaderText="Delete" ShowDeleteButton="true" ShowHeader="true" />
</Columns>
</asp:GridView>
Can anyone provide a relevant solution to this?
you put the ddl no in the footer template but you're only checking for that in the (e.Row.RowType == DataControlRowType.DataRow) Change that to FooterRow and it should find it
change the above line to
if(e.Row.RowType == DataControlRowType.Footer && e.Row.DataItem != null)
<%--DataKeyNames="Environment_ID"--%>
' />
<%--
'>
' />
--%>
' />
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="lblapp" runat="server" Text='<%# Eval("AppName") %>'></asp:Label>
</ItemTemplate>
<FooterTemplate>
<asp:DropDownList ID="ddlAppFooter" class="SearchBoxRTD" runat="server" DataTextField="AppName"
DataValueField="SNO">
</asp:DropDownList>
</FooterTemplate>
<HeaderStyle HorizontalAlign="Left" />
</asp:TemplateField>
<asp:TemplateField HeaderText="TestType" HeaderStyle-Width="50">
<EditItemTemplate>
<asp:DropDownList ID="ddlTestTypeDataRow" class="SearchBoxRTD" runat="server" DataTextField="Testingtypedescription"
DataValueField="TestingTypeID">
</asp:DropDownList>
<asp:HiddenField ID="hdnTesttype" runat="server" Value='<%# Bind("Testtype") %>' />
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="lblTestType" runat="server" Text='<%# Eval("Testingtypedescription") %>'></asp:Label>
</ItemTemplate>
<FooterTemplate>
<asp:DropDownList ID="ddlTestTypeFooter" class="SearchBoxRTD" runat="server" DataTextField="Testingtypedescription"
DataValueField="TestingTypeID">
</asp:DropDownList>
</FooterTemplate>
<HeaderStyle HorizontalAlign="Left" />
</asp:TemplateField>
<asp:TemplateField HeaderText="Scenario Type" HeaderStyle-Width="50">
<EditItemTemplate>
<asp:DropDownList ID="ddlScenarioTypeDataRow" class="SearchBoxRTD" runat="server" DataTextField="ScenarioTypedescription"
DataValueField="ScenarioTypeID">
</asp:DropDownList>
<asp:HiddenField ID="hdnScenariotype" runat="server" Value='<%# Bind("ScenarioTypeID") %>' />
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="lblScenarioType" runat="server" Text='<%# Eval("ScenarioTypedescription") %>'></asp:Label>
</ItemTemplate>
<FooterTemplate>
<asp:DropDownList ID="ddlScenarioTypeFooter" class="SearchBoxRTD" runat="server"
DataTextField="ScenarioTypedescription" DataValueField="ScenarioTypeID">
</asp:DropDownList>
</FooterTemplate>
<HeaderStyle HorizontalAlign="Left" />
</asp:TemplateField>
<asp:TemplateField HeaderText="Scenario">
<EditItemTemplate>
<asp:TextBox ID="txtScenario" runat="server" Text='<%# Bind("Scenario") %>'></asp:TextBox>
<asp:RequiredFieldValidator ID="RFDGEdUI" runat="server" Font-Bold="true" ErrorMessage="*"
ControlToValidate="txtScenario" ValidationGroup="EditScenario"></asp:RequiredFieldValidator>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="LblScenario" runat="server" Text='<%# Bind("Scenario") %>' />
</ItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtfootScenario" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator ID="RFDGScenario" runat="server" Font-Bold="true" ErrorMessage="*"
ControlToValidate="txtfootScenario" ValidationGroup="AddScenario"></asp:RequiredFieldValidator>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Status">
<EditItemTemplate>
<asp:CheckBox ID="chkScenariostatus" runat="server" Checked='<%# Bind("Status") %>' />
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="LblScenarioStatus" runat="server" Text='<%# Bind("Status") %>' />
</ItemTemplate>
<FooterTemplate>
<asp:CheckBox ID="chkScenariofooter" runat="server" />
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Edit" ShowHeader="False">
<EditItemTemplate>
<asp:LinkButton ID="lbkUpdateScenario" runat="server" ValidationGroup="EditScenario"
CausesValidation="True" CommandName="Update" Text="Update"></asp:LinkButton>
<asp:LinkButton ID="lnkCancelScenario" runat="server" CausesValidation="False" CommandName="Cancel"
Text="Cancel"></asp:LinkButton>
</EditItemTemplate>
<FooterTemplate>
<asp:LinkButton ID="lnkAddScenario" runat="server" ValidationGroup="AddScenario"
CausesValidation="True" CommandName="Insert" Text="Insert"></asp:LinkButton>
</FooterTemplate>
<ItemTemplate>
<asp:LinkButton ID="lnkEditScenario" runat="server" CausesValidation="False" CommandName="Edit"
Text="Edit"></asp:LinkButton>
</ItemTemplate>
<HeaderStyle HorizontalAlign="Left" />
</asp:TemplateField>
</Columns>
<EmptyDataTemplate>
No Applications available!
</EmptyDataTemplate>
</asp:GridView>
--------------------------------CS--------------------------------------------------------
protected void grdScenario_RowDataBound(object sender, GridViewRowEventArgs e)
{
try
{
DataSet ds = GetData("qtp_getservice");
if (e.Row.RowType == DataControlRowType.DataRow)
{
//services,environment,platform
// bool flag = false;
if (e.Row.RowType == DataControlRowType.DataRow && (e.Row.RowState == DataControlRowState.Normal || e.Row.RowState == DataControlRowState.Alternate))
{
Label lbl = (Label)e.Row.FindControl("LblScenarioStatus");
if (null != lbl && lbl.Text != "")
{
lbl.Text = (string.Compare(lbl.Text, "True", true) == 0) ? "Enabled" : "Disabled";
}
}
if (e.Row.RowType == DataControlRowType.DataRow && (e.Row.RowState & DataControlRowState.Edit) == DataControlRowState.Edit)
// {
// for (int i = 0; i < grdScenario.Rows.Count ; i++)
// {
// foreach (GridViewRow gvRow in grdScenario.Rows)
{
DropDownList ddlApp = (DropDownList)e.Row.FindControl("ddlAppDataRow");
DropDownList ddlTT = (DropDownList)e.Row.FindControl("ddlTestTypeDataRow");
DropDownList ddlST = (DropDownList)e.Row.FindControl("ddlScenarioTypeDataRow");
//Label lblapp = ((Label)e.Row.Cells[2].FindControl("lblapp"));
//Label lblTestType = ((Label)e.Row.Cells[3].FindControl("lblTestType"));
//Label lblScenarioType = ((Label)e.Row.Cells[4].FindControl("lblScenarioType"));
// Label lblapp = ((Label)grdScenario.Rows[i].Cells[2].FindControl("lblapp"));
//Label lblTestType = ((Label)grdScenario.Rows[i].Cells[3].FindControl("lblTestType"));
// Label lblScenarioType = ((Label)grdScenario.Rows[i].Cells[4].FindControl("lblScenarioType"));
if (ddlApp != null)
{
HiddenField hdnAppid = (HiddenField)e.Row.FindControl("hdnAppid");
ddlApp.DataSource = ds.Tables[4].DefaultView;
ddlApp.DataTextField = "AppName";
ddlApp.DataValueField = "SNO";
ddlApp.DataBind();
//ddlApp.SelectedIndex = ddlApp.Items.IndexOf(ddlApp.Items.FindByText(grdScenario.DataKeys[e.Row.RowIndex].Values[1].ToString()));
//ddlApp.SelectedItem.Text = lblapp.Text.ToString();
ddlApp.SelectedValue = hdnAppid.Value;
}
if (ddlTT != null)
{
HiddenField hdnTesttype = (HiddenField)e.Row.FindControl("hdnTesttype");
ddlTT.DataSource = ds.Tables[5].DefaultView;
ddlTT.DataTextField = "Testingtypedescription";
ddlTT.DataValueField = "TestingTypeID";
ddlTT.DataBind();
//ddlTT.SelectedItem.Text = lblTestType.Text.ToString();
ddlTT.SelectedValue = hdnTesttype.Value;
//ddlTT.SelectedIndex = ddlTT.Items.IndexOf(ddlTT.Items.FindByText(grdservices.DataKeys[e.Row.RowIndex].Values[2].ToString()));
}
if (ddlST != null)
{
HiddenField hdnScenariotype = (HiddenField)e.Row.FindControl("hdnScenariotype");
ddlST.DataSource = ds.Tables[6].DefaultView;
ddlST.DataTextField = "ScenarioTypeDescription";
ddlST.DataValueField = "ScenarioTypeID";
ddlST.DataBind();
ddlST.SelectedValue = hdnScenariotype.Value;
//ddlST.SelectedItem.Text = lblScenarioType.Text.ToString();
//ddlST.SelectedIndex = ddlST.Items.IndexOf(ddlST.Items.FindByText(grdScenario.DataKeys[e.Row.RowIndex].Values[3].ToString()));
}
}
// }
//// }
}
if (e.Row.RowType == DataControlRowType.Footer)
{
//Bind environment,platform at footer.
DropDownList cmbNewType = (DropDownList)e.Row.FindControl("ddlAppFooter");
cmbNewType.DataSource = ds.Tables[4].DefaultView;
cmbNewType.DataBind();
DropDownList cmbNewType1 = (DropDownList)e.Row.FindControl("ddlTestTypeFooter");
cmbNewType1.DataSource = ds.Tables[5].DefaultView;
cmbNewType1.DataBind();
DropDownList cmbNewType2 = (DropDownList)e.Row.FindControl("ddlScenarioTypeFooter");
cmbNewType2.DataSource = ds.Tables[6].DefaultView;
cmbNewType2.DataBind();
}
}
catch (System.Exception) { }
}
I have a GridView in my page :
<asp:GridView ID="GridView1" runat="server" AllowPaging="True" BackColor="White"
AutoGenerateColumns="False" EmptyDataText="No data available." BorderColor="#DEDFDE"
BorderStyle="None" BorderWidth="1px" CellPadding="4" Width="729px" ForeColor="Black"
GridLines="Vertical" OnSelectedIndexChanged="GridView1_SelectedIndexChanged">
<RowStyle BackColor="#F7F7DE" />
<Columns>
<asp:TemplateField HeaderText="TransactionKey" SortExpression="TransactionKey">
<EditItemTemplate>
<asp:TextBox ID="TextBoxGridViewTransactionKey" runat="server" Text='<%# Bind("TextBoxTransactionKey") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="LabelGridViewTransactionKey" runat="server" Text='<%# Bind("TextBoxTransactionKey") %>'></asp:Label>
</ItemTemplate>
<HeaderStyle Font-Size="14px" />
<ItemStyle Font-Size="12px" />
</asp:TemplateField>
<asp:TemplateField HeaderText="TerminalID" SortExpression="TerminalID">
<EditItemTemplate>
<asp:TextBox ID="TextBoxGridViewTerminalID" runat="server" Text='<%# Bind("TextBoxTerminalID") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="LabelGridViewTerminalID" runat="server" Text='<%# Bind("TextBoxTerminalID") %>'></asp:Label>
</ItemTemplate>
<HeaderStyle Font-Size="14px" />
<ItemStyle Font-Size="12px" />
</asp:TemplateField>
<asp:TemplateField HeaderText="MerchantID" SortExpression="MerchantID">
<EditItemTemplate>
<asp:TextBox ID="TextBoxGridViewMerchantID" runat="server" Text='<%# Bind("TextBoxMerchantID") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="LabelGridViewMerchantID" runat="server" Text='<%# Bind("TextBoxMerchantID") %>'></asp:Label>
</ItemTemplate>
<HeaderStyle Font-Size="14px" />
<ItemStyle Font-Size="12px" />
</asp:TemplateField>
<asp:TemplateField HeaderText="شماره حساب" SortExpression="شماره حساب">
<EditItemTemplate>
<asp:TextBox ID="TextBoxGridViewBankAccount" runat="server" Text='<%# Bind("TextBoxBankAccount") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="LabelGridViewBankAccount" runat="server" Text='<%# Bind("TextBoxBankAccount") %>'></asp:Label>
</ItemTemplate>
<HeaderStyle Font-Size="14px" />
<ItemStyle Font-Size="12px" />
</asp:TemplateField>
<asp:TemplateField HeaderText="نام بانک" SortExpression="نام بانک">
<EditItemTemplate>
<asp:TextBox ID="TextBoxGridViewBankName" runat="server" Text='<%# Bind("BankName") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="LabelGridViewBankName" runat="server" Text='<%# Bind("BankName") %>'></asp:Label>
</ItemTemplate>
<HeaderStyle Font-Size="14px" />
<ItemStyle Font-Size="12px" />
</asp:TemplateField>
<asp:CommandField ShowSelectButton="True" >
<ItemStyle Font-Size="12px" />
</asp:CommandField>
</Columns>
<FooterStyle BackColor="#CCCC99" />
<PagerStyle ForeColor="Black" HorizontalAlign="Right" BackColor="#F7F7DE" />
<SelectedRowStyle BackColor="#CE5D5A" Font-Bold="True" ForeColor="White" />
<HeaderStyle BackColor="#6B696B" Font-Bold="True" ForeColor="White" />
<AlternatingRowStyle BackColor="White" />
</asp:GridView>
I set the DataSource with the follwing code :
protected void Page_Load(object sender, EventArgs e)
{
try
{
LabelTitr.Text = "Add Banks";
LabelResult.Text = "";
if (Session["Username"] != null)
{
string permission = "";
bool login = PublicMethods.CheckUsernamePass(Session["Username"].ToString(), Session["Password"].ToString(), out permission);
if (!login)
{
permission = "";
Response.Redirect("../Default.aspx");
Session["Username"] = Session["Password"] = null;
return;
}
}
else
{
Response.Redirect("../Default.aspx");
Session["Username"] = Session["Password"] = null;
return;
}
if (!IsPostBack)
BindDataToGridView1();
}
catch (Exception ex)
{
LabelResult.Text = ex.Message;
}
}
void BindDataToGridView1()
{
try
{
DataSet1 dataSet = new DataSet1();
DataClasses2DataContext dbc2 = new DataClasses2DataContext();
var Definitions = dbc2.Definitions;
if (Definitions.Count() <= 0) return;
foreach (var Definition in Definitions)
{
string bankName = dbc2.Banks.Where(c => c.BankID == Definition.BankID).First().BankName;
string CheckBox = "<input name=\"CheckBoxSubmitChanges\" type=\"checkbox\" value=" + Definition.DefinitionID + " />";
dataSet.DataTableBanks.Rows.Add(bankName, Definition.BankAccount, Definition.MerchantID, Definition.TerminalID, Definition.TerminalID);
GridView1.DataSource = dataSet.DataTableBanks;
}
GridView1.DataBind();
}
catch (Exception ex)
{
LabelResult.Text = ex.Message;
}
}
and this is GridView1_SelectedIndexChanged method :
protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
{
GridViewRow row = GridView1.SelectedRow;
string temp = row.Cells[4].Text;
LabelResult.Text = temp;
}
But always temp string is empty !!!
What's wrong with it ?
Thanks
If it's a TemplateField, you have to use the FindControl("control ID") option, not the text fo the cell. I count cell 4 as being a templatefield...
There is no Text as your data is stored in controls. You need to search for the control you want and pull the Text out of.
Eg:
protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
{
GridViewRow row = GridView1.SelectedRow;
string temp = row.Cells[4].FindControl('LabelGridViewBankName').Text;
LabelResult.Text = temp;
}
Optionally you could could key off the DataKey property if you are using it and then use it to search your datasource for the value you want.
//this will give you control over the textbox object
var field = (TextBox)(GridView1.Rows[e.RowIndex].FindControl("your_control_ID"));
//and here you can access the text
string temp = field.Text;
I'm trying to give the user the ability to create a new record from the footer row and my event handler doesn't seem to be working... or maybe I'm going at this all wrong.
The insert button that I enabled in the gridview doesn't work either...checkout the site at http://aisched.engr.oregonstate.edu/admin/courses.aspx
Here is my code in front and behind:
public partial class admin_courses : System.Web.UI.Page
{
public Table table;
ListDictionary listValues = new ListDictionary();
TextBox textBox1 = new TextBox(); //Name
TextBox textBox2 = new TextBox(); //CR
TextBox textBox3 = new TextBox(); //CourseNum
TextBox textBox4 = new TextBox(); //Dept
protected void Page_Init()
{
}
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType != DataControlRowType.Footer) return; //Escape if not footer
textBox1.ID = "name";
textBox1.Width = 250;
textBox2.ID = "credit_hours";
textBox2.Width = 25;
textBox3.ID = "dept";
textBox3.Width = 30;
textBox4.ID = "class";
textBox4.Width = 25;
LinkButton add = new LinkButton();
add.ID = "add";
add.Text = "Add course";
add.CommandName = "add";
add.Click += new EventHandler(add_Click);
e.Row.Cells[1].Controls.Add(textBox1);
e.Row.Cells[2].Controls.Add(textBox2);
e.Row.Cells[3].Controls.Add(textBox3);
e.Row.Cells[4].Controls.Add(textBox4);
e.Row.Cells[5].Controls.Add(add);
}
public void add_Click(object sender, EventArgs e)
{
Response.Write("you Clicked Add Course!");
if (textBox1.Text != null && textBox2.Text != null && textBox3.Text != null && textBox4.Text != null) {
listValues.Add("name", textBox1.Text);
listValues.Add("credit_hours", textBox2.Text);
listValues.Add("dept", textBox4.Text); //For Visual
listValues.Add("class", textBox3.Text);
}
LinqDataSource1.Insert(listValues);
Response.Redirect("~/admin/courses.aspx");
}
}
<%# Page Language="C#" MasterPageFile="~/admin.master" AutoEventWireup="true" CodeFile="courses.aspx.cs" Inherits="admin_courses" Title="OSU Aisched | Admin - Courses" %>
<%# Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="asp" %>
<asp:Content ID="Content1" ContentPlaceHolderID="admin_nav_links" Runat="Server">
<ul id="main">
<li>Overview</li>
<li>Users</li>
<li class="current_page_item">Courses</li>
<li>Programs</li>
<li>Sections</li>
<li>Import</li>
<li>Logs</li>
</ul>
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server">
<form id="Form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
<asp:LinqDataSource ID="LinqDataSource1" runat="server"
ContextTypeName="DataClassesDataContext" EnableDelete="True"
EnableInsert="True" EnableUpdate="True" TableName="courses">
</asp:LinqDataSource>
<h1><a>Courses</a></h1>
<asp:UpdateProgress ID="UpdateProgress1" runat="server">
</asp:UpdateProgress>
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
DataKeyNames="course_id" DataSourceID="LinqDataSource1"
BackColor="#DEBA84" BorderColor="#DEBA84" BorderStyle="None" BorderWidth="1px"
CellPadding="3" CellSpacing="2" AllowSorting="True" ShowFooter="True"
OnRowDataBound="GridView1_RowDataBound" >
<RowStyle BackColor="#FFF7E7" ForeColor="#8C4510" />
<Columns>
<asp:BoundField DataField="course_id" HeaderText="ID"
ReadOnly="True" SortExpression="course_id" />
<asp:BoundField DataField="name" HeaderText="Name" SortExpression="name" />
<asp:BoundField DataField="credit_hours" HeaderText="CR"
SortExpression="credit_hours" />
<asp:BoundField DataField="dept" HeaderText="Dept" SortExpression="dept" />
<asp:BoundField DataField="class" HeaderText="#" SortExpression="class" />
<asp:CommandField DeleteImageUrl="~/media/delete.png" ShowDeleteButton="True"
ShowEditButton="True" ShowInsertButton="True"/>
</Columns>
<FooterStyle BackColor="#F7DFB5" ForeColor="#8C4510" />
<PagerStyle ForeColor="#8C4510" HorizontalAlign="Center" />
<SelectedRowStyle BackColor="#738A9C" Font-Bold="True" ForeColor="White" />
<HeaderStyle BackColor="#A55129" Font-Bold="True" ForeColor="White" />
</asp:GridView>
<br />
<asp:HyperLink ID="HyperLink1" runat="server" Target="~/admin/addCourse.aspx" Enabled="true"NavigateUrl="~/admin/addCourse.aspx" Text="Add New course"></asp:HyperLink>
<br />
</form>
</asp:Content>
I expect (or at least I certainly hope) there's a better way to do this, but try this:
<asp:LinqDataSource runat="server" ID="LinqDataSource1" ContextTypeName="Courses.DataClassesDataContext" TableName="Courses" EnableDelete="True" EnableUpdate="True" EnableInsert="True" />
<h1>
<a>
Courses</a></h1>
<asp:UpdateProgress ID="UpdateProgress1" runat="server">
</asp:UpdateProgress>
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataKeyNames="course_id"
DataSourceID="LinqDataSource1" BackColor="#DEBA84" BorderColor="#DEBA84" BorderStyle="None"
BorderWidth="1px" CellPadding="3" CellSpacing="2" AllowSorting="True"
ShowFooter="True">
<Columns>
<asp:BoundField DataField="course_id" HeaderText="course_id" ReadOnly="True" SortExpression="course_id"
InsertVisible="False" />
<asp:TemplateField HeaderText="name" SortExpression="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="NameTextBox" runat="server" />
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="credit_hours" SortExpression="credit_hours">
<EditItemTemplate>
<asp:TextBox ID="TextBox2" runat="server" Text='<%# Bind("credit_hours") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label2" runat="server" Text='<%# Bind("credit_hours") %>'></asp:Label>
</ItemTemplate>
<FooterTemplate>
<asp:TextBox ID="HoursTextBox" runat="server" />
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="dept" SortExpression="dept">
<EditItemTemplate>
<asp:TextBox ID="TextBox3" runat="server" Text='<%# Bind("dept") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label3" runat="server" Text='<%# Bind("dept") %>'></asp:Label>
</ItemTemplate>
<FooterTemplate>
<asp:TextBox ID="DeptTextBox" runat="server" />
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="class" SortExpression="class">
<EditItemTemplate>
<asp:TextBox ID="TextBox4" runat="server" Text='<%# Bind("class") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label4" runat="server" Text='<%# Bind("class") %>'></asp:Label>
</ItemTemplate>
<FooterTemplate>
<asp:TextBox ID="ClassTextBox" runat="server" />
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField ShowHeader="False">
<EditItemTemplate>
<asp:LinkButton ID="LinkButton1" runat="server" CausesValidation="True" CommandName="Update"
Text="Update"></asp:LinkButton>
<asp:LinkButton ID="LinkButton2" runat="server" CausesValidation="False" CommandName="Cancel"
Text="Cancel"></asp:LinkButton>
</EditItemTemplate>
<ItemTemplate>
<asp:LinkButton ID="LinkButton1" runat="server" CausesValidation="False" CommandName="Edit"
Text="Edit"></asp:LinkButton>
<asp:LinkButton ID="LinkButton2" runat="server" CausesValidation="False" CommandName="Delete"
Text="Delete"></asp:LinkButton>
</ItemTemplate>
<FooterTemplate>
<asp:LinkButton ID="AddLinkButton" runat="server" CommandName="Add" Text="Add" CausesValidation="true" />
</FooterTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
protected void Page_Load(object sender, EventArgs e)
{
try
{
if (IsPostBack)
{
// We are in a Postback so check to see if the AddLinkButton was clicked
String eventTarget = Request.Form["__EVENTTARGET"].ToString();
if (eventTarget.EndsWith("addlinkbutton",StringComparison.InvariantCultureIgnoreCase))
{
// We are adding a new row so build a ListDictionary with the controls from the footer row
ListDictionary values = new ListDictionary();
values.Add("name", ((TextBox)GridView1.FooterRow.FindControl("NameTextBox")).Text);
values.Add("credit_hours", ((TextBox)GridView1.FooterRow.FindControl("HoursTextBox")).Text);
values.Add("dept", ((TextBox)GridView1.FooterRow.FindControl("DeptTextBox")).Text);
values.Add("class", ((TextBox)GridView1.FooterRow.FindControl("ClassTextBox")).Text);
// Pass the ListDictionary to the data source to send off to the database
LinqDataSource1.Insert(values);
// Refresh the grid so it shows the row we just added
GridView1.DataBind();
}
}
}
catch (Exception)
{
throw;
}
}
I couldn't make it work without writing code manually to do the Insert. Handling the AddLinkButton_Click event in the Page_Load event by examining the EventTarget hidden field to see if it ends with 'addlinkbutton' feels quite wrong, but it works.
A Sample pseudo code which can add from grid view footer, Initially data's are saved under View State, Using button click event to check the ViewState and insert the new data to the table.
aspx code
<asp:GridView ID="gvUser" runat="server" AutoGenerateColumns="false" ShowFooter="true" OnRowDataBound="gvUser_RowDataBound"
OnRowCommand="gvUser_RowCommand" OnRowDeleting="gvUser_RowDeleting" OnRowEditing="gvUser_RowEditing" CssClass="table table-bordered table-hover table-striped">
<EmptyDataTemplate>
No Data Found
</EmptyDataTemplate>
<Columns>
<asp:TemplateField HeaderText="User Details" HeaderStyle-Width="25%">
<ItemTemplate>
<asp:Label ID="lblCourse" runat="server" Text='<%# Eval("Details") %>'></asp:Label>
</ItemTemplate>
<FooterTemplate>
<asp:DropDownList ID="ddlDetails" runat="server" DataTextField="Name" DataValueField="ID" CssClass="form-control" />
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="user Check One" HeaderStyle-Width="5%" ItemStyle-HorizontalAlign="Center" FooterStyle-HorizontalAlign="Center">
<ItemTemplate>
<asp:Image ID="imgCheckOne" runat="server" Width="20" Height="20" ImageUrl='<%# (Boolean.Parse(Eval("CheckOne").ToString())==false) ? "" : "../Contents/Images/tick.svg" %>' />
</ItemTemplate>
<FooterTemplate>
<asp:CheckBox ID="chkCheckOne" runat="server" CssClass="i-checks" />
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="HR Rec." HeaderStyle-Width="5%" ItemStyle-HorizontalAlign="Center" FooterStyle-HorizontalAlign="Center">
<ItemTemplate>
<asp:Image ID="imgCheckTwo" runat="server" Width="20" Height="20" ImageUrl='<%# (Boolean.Parse(Eval("CheckTwo").ToString())==false) ? "" : "../Contents/Images/tick.svg" %>' />
</ItemTemplate>
<FooterTemplate>
<asp:CheckBox ID="chkCheckTwo" runat="server" CssClass="i-checks" />
</FooterTemplate>
<ItemStyle Wrap="true" />
</asp:TemplateField>
<asp:TemplateField ItemStyle-HorizontalAlign="Center" HeaderStyle-Width="5%">
<ItemTemplate>
<asp:ImageButton ID="imgBtnEdit" runat="server" CausesValidation="false" CommandName="Edit" ImageUrl="~/Contents/Images/pencil.svg" Width="20" Height="20"
ToolTip="Edit"></asp:ImageButton>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField ItemStyle-HorizontalAlign="Center" FooterStyle-HorizontalAlign="Center" HeaderStyle-Width="5%">
<ItemTemplate>
<asp:ImageButton ID="imgBtnDelete" runat="server" CausesValidation="false" CommandName="Delete" ImageUrl="~/Contents/Images/remove.svg" Width="20" Height="20"
ToolTip="Delete"></asp:ImageButton>
</ItemTemplate>
<FooterTemplate>
<asp:ImageButton ID="imgBtnAdd" runat="server" CausesValidation="true" CommandName="Add" ImageUrl="~/Contents/Images/add.svg" Width="20" Height="20"
ToolTip="Add"></asp:ImageButton>
</FooterTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Server side code
protected void gvUser_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.Footer)
{
List<TableOne> controlDetails = new List<TableOne>();
controlDetails = dc.TableOne.Where(condition).ToList();
controlDetails.Insert(0, new TableOne() { ID = 0, Name = "Select Details" });
DropDownList ddlDetails = (e.Row.FindControl(ddlDetails) as DropDownList);
ddlDetails.DataSource = controlDetails;
ddlDetails.DataTextField = "Name";
ddlDetails.DataValueField = "ID";
ddlDetails.DataBind();
}
}
protected void gvUser_RowCommand(object sender, GridViewCommandEventArgs e)
{
try
{
if (e.CommandName == "Delete")
{
GridViewRow gvr = (GridViewRow)(((ImageButton)e.CommandSource).NamingContainer);
int RowIndex = gvr.RowIndex;
DataTable dtUserDetails = (DataTable)ViewState["gvUser"];
DataRow dr = dtUserDetails.Rows[RowIndex];
dr.Delete();
gvUser.Rows[RowIndex].Visible = false;
}
else if (e.CommandName == "Edit")
{
DropDownList ddlDetails = (DropDownList)((GridView)sender).FooterRow.FindControl("ddlDetails");
CheckBox CheckOne = (CheckBox)((GridView)sender).FooterRow.FindControl("CheckOne");
CheckBox CheckTwo = (CheckBox)((GridView)sender).FooterRow.FindControl("CheckTwo");
GridViewRow gvr = (GridViewRow)(((ImageButton)e.CommandSource).NamingContainer);
int RowIndex = gvr.RowIndex;
DataTable dtUserDetails = (DataTable)ViewState["gvUser"];
DataRow dr = dtUserDetails.Rows[RowIndex];
ddlDetails.SelectedValue = dr["DetailID"].ToString();
CheckOne.Checked = Convert.ToBoolean(dr["CheckOne"]);
CheckTwo.Checked = Convert.ToBoolean(dr["CheckTwo"]);
dr.Delete();
}
else if (e.CommandName == "Add")
{
DropDownList ddlDetails = (DropDownList)((GridView)sender).FooterRow.FindControl("ddlDetails");
CheckBox CheckOne = (CheckBox)((GridView)sender).FooterRow.FindControl("CheckOne");
CheckBox CheckTwo = (CheckBox)((GridView)sender).FooterRow.FindControl("CheckTwo");
if (ViewState["gvUser"] != null)
{
DataTable existingTable = (DataTable)ViewState["gvUser"];
existingTable.Rows.Add(0, Convert.ToInt32(hdnUserID.Value), 0, ddlDetails.SelectedItem.Value, ddlDetails.SelectedItem.Text, CheckOne.Checked, CheckTwo.Checked);
ViewState["gvUser"] = existingTable;
gvUser.DataSource = existingTable;
gvUser.DataBind();
}
else
{
DataTable dtUsers = new DataTable();
dtUsers.Columns.Add("ID");
dtUsers.Columns.Add("UserID");
dtUsers.Columns.Add("DetailsID");
dtUsers.Columns.Add("Details");
dtUsers.Columns.Add("CheckOne");
dtUsers.Columns.Add("CheckTwo");
dtUsers.Rows.Add(0, Convert.ToInt32(hdnUserID.Value), 0, ddlDetails.SelectedItem.Value, ddlDetails.SelectedItem.Text, CheckOne.Checked, CheckTwo.Checked);
ViewState["gvUser"] = dtUsers;
gvUser.DataSource = dtUsers;
gvUser.DataBind();
}
}
}
catch (Exception)
{
}
}
//dummy function to avoid runtime grid error
protected void gvCandidateJD_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
}
//dummy function to avoid runtime grid error
protected void gvCandidateJD_RowEditing(object sender, GridViewEditEventArgs e)
{
}
protected void btnSave_Click(object sender, EventArgs e)
{
if (ViewState["gvUser"] != null)
{
TableOne userInfo = null;
List<TableOne> userDetails = new List<TableOne>();
DataTable userSpecificDetails = (DataTable)ViewState["gvUser"];
for (int i = 0; i < userSpecificDetails.Rows.Count; i++)
{
userInfo = new TableOne();
userInfo.UserID = UserID; //supply value
foreach (DataColumn col in userSpecificDetails.Columns)
{
switch (col.ColumnName)
{
case "DetailsID":
userInfo.DetailsID = Convert.ToInt16(userSpecificDetails.Rows[i][col.ColumnName]);
break;
case "CheckOne":
userInfo.CheckOne = Convert.ToBoolean(userSpecificDetails.Rows[i][col.ColumnName]);
break;
case "CheckTwo":
userInfo.CheckTwo = Convert.ToBoolean(userSpecificDetails.Rows[i][col.ColumnName]);
break;
}
}
userDetails.Add(userInfo);
}
if (userDetails.Count > 0)
{
dc.TableOne.InsertAllOnSubmit(userDetails);
dc.SubmitChanges();
}
}
}