How to add RequiredExpressionValidator to the "Cantitate" field - c#

I have a shopping cart that can be updated by the user. I want to add a validation method to the "Cantitate" field, so that the user can only add positive integers.
html
<asp:GridView ID="CartList" runat="server" AutoGenerateColumns="False" ShowFooter="True" GridLines="Vertical" CellPadding="4"
ItemType="Magazin.Models.CartItem" SelectMethod="GetShoppingCartItems"
CssClass="table table-striped table-bordered">
<Columns>
<asp:BoundField DataField="ProductID" HeaderText="Nr. articol" SortExpression="ProductID" />
<asp:BoundField DataField="Product.ProductName" HeaderText="Denumire" />
<asp:BoundField DataField="Product.UnitPrice" HeaderText="Preț (per bucată)" DataFormatString="{0:c}" />
<asp:TemplateField HeaderText="Cantitate">
<ItemTemplate>
<asp:TextBox ID="PurchaseQuantity" Width="40" runat="server" Text="<%#: Item.Quantity %>"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Total de plată pentru acest produs">
<ItemTemplate>
<%#: String.Format("{0:c}", ((Convert.ToDouble(Item.Quantity)) * Convert.ToDouble(Item.Product.UnitPrice)))%>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Șterge">
<ItemTemplate>
<asp:CheckBox ID="Remove" runat="server"></asp:CheckBox>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Here is the UpdateCartItems:
public List<CartItem> UpdateCartItems()
{
using (ShoppingCartActions usersShoppingCart = new ShoppingCartActions())
{
String cartId = usersShoppingCart.GetCartId();
ShoppingCartActions.ShoppingCartUpdates[] cartUpdates = new ShoppingCartActions.ShoppingCartUpdates[CartList.Rows.Count];
for (int i = 0; i < CartList.Rows.Count; i++)
{
IOrderedDictionary rowValues = new OrderedDictionary();
rowValues = GetValues(CartList.Rows[i]);
cartUpdates[i].ProductId = Convert.ToInt32(rowValues["ProductID"]);
CheckBox cbRemove = new CheckBox();
cbRemove = (CheckBox)CartList.Rows[i].FindControl("Remove");
cartUpdates[i].RemoveItem = cbRemove.Checked;
TextBox quantityTextBox = new TextBox();
quantityTextBox = (TextBox)CartList.Rows[i].FindControl("PurchaseQuantity");
cartUpdates[i].PurchaseQuantity = Convert.ToInt16(quantityTextBox.Text.ToString());
}
usersShoppingCart.UpdateShoppingCartDatabase(cartId, cartUpdates);
CartList.DataBind();
lblTotal.Text = String.Format("{0:c}", usersShoppingCart.GetTotal());
return usersShoppingCart.GetCartItems();
}
}
The update button of the shopping cart, that updates the cart by calling the UpdateCartItems
protected void UpdateBtn_Click(object sender, EventArgs e)
{
UpdateCartItems();
}

<asp:GridView ID="CartList" runat="server" AutoGenerateColumns="False">
<Columns>
<asp:BoundField DataField="Message" HeaderText="Nr. articol" SortExpression="ProductID" />
<asp:TemplateField HeaderText="Cantitate">
<ItemTemplate>
<asp:TextBox ID="YourTextBox" runat="server" />
<asp:CompareValidator runat="server"
ControlToValidate="YourTextBox"
Operator="DataTypeCheck"
Type="Integer"
ErrorMessage="Enter a valid integer"
Display="Dynamic" />
<asp:CompareValidator runat="server"
ControlToValidate="YourTextBox"
Operator="GreaterThanEqual"
ValueToCompare="0"
Type="Integer"
ErrorMessage="The integer cannot be less than zero"
Display="Dynamic" />
<%--<asp:TextBox ID="PurchaseQuantity" Width="40" runat="server" Text="" TextMode="Number" min="0"></asp:TextBox>
<asp:RegularExpressionValidator runat="server" Display="Dynamic" ControlToValidate="PurchaseQuantity" ErrorMessage="Enter a valid value" ForeColor="Red" ValidationExpression="\s+\d{1,6}\s+"></asp:RegularExpressionValidator>--%>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>

Related

Cell Text Always &nbsp:

I want to display the text of a specific cell in a textbox whenever I select a row from my gridview but whenever i do this "&nbsp" is the only text that I get even though the cell is not empty. Data on the gridview is bound from my database and I made a function where all the data from my database will be bound on my gridview. Below is the code that I'm using.
textbox1.Text = myGridView.SelectedRow.Cells[3].Text;
Markup
<asp:GridView ID="TraineeGrid" runat="server" AutoGenerateSelectButton ="true" AllowSorting="True" ShowHeader="true"
ShowFooter="false" AutoGenerateColumns="False" AutoGenerateEditButton="false" ScrollBars="Auto"
OnRowEditing="TraineeGrid_RowEditing"
OnRowUpdating="TraineeGrid_RowUpdating" OnRowCancelingEdit="TraineeGrid_RowCancelingEdit"
DataKeyNames="ID" Width="100%"
CellPadding="4" ForeColor="#333333" GridLines="None" HorizontalAlign="Center"
EditRowStyle-VerticalAlign="Middle" OnInit="Page_Load" OnRowDataBound="TraineeGrid_RowDataBound" OnSelectedIndexChanging="TraineeGrid_SelectedIndexChanging" OnSelectedIndexChanged="TraineeGrid_SelectedIndexChanged">
<AlternatingRowStyle BackColor="White" />
<Columns>
<asp:TemplateField HeaderText="Delegates Name">
<ItemStyle HorizontalAlign="Center" Width="125px" />
<HeaderTemplate>
<asp:LinkButton ID="lbDelegate" runat="server" Text="Delegate Name" CommandName="Sort"
CommandArgument="Delegate" ForeColor="White" Font-Underline="False"></asp:LinkButton>
<br />
<asp:TextBox ID="newDelegate" TabIndex="1" runat="server"></asp:TextBox>
</HeaderTemplate>
<ItemTemplate>
<%# Eval("Delegate") %>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtDelegate" runat="server"
Text='<%# Eval("Delegate") %>'/>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Rank/Position">
<ItemStyle HorizontalAlign="Center" Width="125px" />
<HeaderTemplate>
<asp:LinkButton ID="lbRankPos" runat="server" Text="Rank/Position" CommandName="Sort"
CommandArgument="RankPos" ForeColor="White" Font-Underline="False"></asp:LinkButton>
<br />
<asp:TextBox ID="newRankPos" TabIndex="2" runat="server"></asp:TextBox>
</HeaderTemplate>
<ItemTemplate>
<%# Eval("RankPos") %>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtRankPos" runat="server"
Text='<%# Eval("RankPos") %>'/>
</EditItemTemplate>
</asp:TemplateField>
</Columns>
Function that binds Data
private void PopulateData()
{
DataTable dataTable = new DataTable();
using (SqlConnection connection = new SqlConnection(WebConfigurationManager.ConnectionStrings["TestCS"].ConnectionString))
{
string path = "PopulateSQL.txt";
StringBuilder sb = new StringBuilder();
using (StreamReader sr = new StreamReader(path))
{
while (sr.Peek() >= 0)
{
sb.Append(sr.ReadLine());
}
string sql = sb.ToString();
using (SqlCommand cmd = new SqlCommand(sql, connection))
{
using (SqlDataAdapter dataAdapt = new SqlDataAdapter(cmd))
{
dataAdapt.Fill(dataTable);
ViewState["NormalGrid"] = dataTable;
}
}
}
}
if (dataTable.Rows.Count > 0)
{
TraineeGrid.DataSource = dataTable;
TraineeGrid.DataBind();
}
else
{
//Displays 'No Data Found' to gridview if there are no data in table
dataTable.Rows.Add(dataTable.NewRow());
TraineeGrid.DataSource = dataTable;
TraineeGrid.DataBind();
TraineeGrid.Rows[0].Cells.Clear();
TraineeGrid.Rows[0].Cells.Add(new TableCell());
TraineeGrid.Rows[0].Cells[0].ColumnSpan = dataTable.Columns.Count;
TraineeGrid.Rows[0].Cells[0].Text = "No Data Found";
TraineeGrid.Rows[0].Cells[0].HorizontalAlign = HorizontalAlign.Center;
}
}
You can use this: textbox1.Text = Server.HtmlDecode(row.Cells[1].Text.Trim());
In OnSelectedIndexChanged :
protected void OnSelectedIndexChanged1(object sender, EventArgs e)
{
//Get the selected row
GridViewRow row = GridView1.SelectedRow;
if (row != null)
{
// With
// TextBox1.Text = (row.FindControl("lblLocalTime") as Label).Text;
// Without
TextBox1.Text = Server.HtmlDecode(row.Cells[1].Text.Trim());
}
}
Complete Markup:
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false"
OnSelectedIndexChanged="OnSelectedIndexChanged1" AutoGenerateSelectButton="true">
<Columns>
<asp:BoundField DataField="Name" HeaderText="Name" ItemStyle-Width="150" />
<asp:BoundField DataField="City" HeaderText="City" ItemStyle-Width="150" />
</Columns>
I've already found a solution. The problem is Im using TemplateField instead of BoundField that's why I cant use .Cells[] to get the specific cell that I wanted to get. However, if you are using TemplateField you can use .FindControl() and put in the ID of the label where your binding of data happens (ex. Text ='<%# Eval("FirstName") %>'). You can see that I put label on ItemTemplate to call it's ID.
Markup
<asp:TemplateField HeaderText="Delegates Name">
<ItemStyle HorizontalAlign="Center" Width="125px" />
<HeaderTemplate>
<asp:LinkButton ID="lbDelegate" runat="server" Text="Delegate Name" CommandName="Sort"
CommandArgument="Delegate" ForeColor="White" Font-Underline="False"></asp:LinkButton>
<br />
<asp:TextBox ID="newDelegate" TabIndex="1" runat="server"></asp:TextBox>
</HeaderTemplate>
<ItemTemplate>
<asp:Label ID="lbName" runat="server" Text = '<%# Eval("Delegate") %>'> </asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtDelegate" runat="server"
Text='<%# Eval("Delegate") %>' />
</EditItemTemplate>
</asp:TemplateField>
Code Behind
Label varName = (Label)rows.FindControl("lbName");
string name = varName.Text;

Input string was not in a correct format in grid view

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)

Gridview footer Textbox javascript call not working after two insert

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)));
}
}
}

Nested grid edit doesn't work

I'm stuck on this problem where I have grid within grid where the nested grid is editable. I can't get the edit working. What's complicates things is that the nested grid is inside a modal popup extender.
It works to the point where I click on the edit button. Then the EmptyDataText property kicks in with the message. If I click on it second time the grid opens in edit mode but the update/cancel buttons don't work. The cancel button when click displays the EmptyDataText property.
Another issue is that this nested grid doesn't use a object data source so I'm going to have to all the updating and deleting in the code file. Not sure now to do that either.
I would like some advice as to how to make this corrected. Here is the code:
<asp:GridView ID="gvForum" runat="server" DataSourceID="odsForumApproval" DataKeyNames="id" Width="200px"
RepeatColumns="1" DataKeyField="id" CssClass="gridview"
AutoGenerateColumns="False" GridLines="None" OnSelectedIndexChanged="_OnCommand">
<AlternatingRowStyle CssClass="altbgcolor" />
<Columns>
<asp:TemplateField >
<ItemTemplate>
<asp:Label runat="server" ID="lblTitle" Text='<%# Bind("Title") %>' />
<asp:Panel id="div" runat="server" align="center" class="confirm" style="display:none" >
<asp:GridView runat="server" ID="gvForumDetail" AutoGenerateColumns="False" DataKeyNames="id"
AllowPaging='true' CssClass="gridview"
AllowSorting="true" PageSize="5" CellPadding="5" OnRowEditing="gvForumDetail_OnRowEditing"
OnRowCancelingEdit="gvForumDetail_CancelRecord" >
<AlternatingRowStyle CssClass="altbgcolor" />
<RowStyle VerticalAlign="Top" HorizontalAlign="Left" />
<HeaderStyle CssClass="greenbar" ForeColor="White" /> <Columns>
<asp:BoundField DataField="id" ReadOnly="true" Visible="false" />
<asp:TemplateField HeaderText="Title">
<ItemTemplate>
<asp:Label runat="server" ID="lblTraining" Text='<%# Bind("title") %>' />
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox runat="server" ID="txtTraining" Text='<%# Bind("title") %>' />
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Post Message">
<ItemTemplate>
<asp:Label runat="server" ID="lblCompletionDate" Width="250" Text='<%# Bind("description") %>' />
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox runat="server" ID="txtDescription" Text='<%# Bind("description") %>' TextMode="MultiLine" Rows="5" Width="250" />
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Posted By">
<ItemTemplate>
<asp:Label runat="server" ID="lblRecurence" Text='<%# Bind("MemberName") %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Posted Date">
<ItemTemplate>
<asp:Label runat="server" ID="lblNotes" Text='<%# Eval("itemdate", "{0:d}") %>' />
</ItemTemplate>
<EditItemTemplate>
<asp:CheckBox runat="server" ID="cbxApproved" Text='<%# Bind("approved") %>' />
</EditItemTemplate>
</asp:TemplateField>
<asp:CommandField ShowCancelButton="true" ShowEditButton="true" ShowDeleteButton="true" />
</Columns>
</asp:GridView>
<br />
<Club:RolloverLink ID="btnClose" runat="server" Text="Close" />
</asp:Panel>
<ajaxToolKit:ModalPopupExtender ID="ModalPopupExtender1" runat="server"
TargetControlID="lblTitle"
PopupControlID="div"
CancelControlID="btnClose"
BackgroundCssClass="modalBackground" />
</ItemTemplate>
</asp:TemplateField>
<asp:CommandField ShowSelectButton="True" />
</Columns>
Code behind:
public void _OnCommand(object sender, EventArgs e)
{
ObjectDataSource ods = new ObjectDataSource();
ods.ID = "ods_ForumDetail";
ods.EnableViewState = true;
ods.TypeName = "ForumApproval";
ods.SelectMethod = "GetForumById";
string id = "";
int rowIndex = gvForum.SelectedIndex;
id = gvForum.DataKeys[rowIndex].Value.ToString();
ods.SelectParameters.Add("id", System.TypeCode.Int32, id);
var ModalPopupExtender1 = (ModalPopupExtender)(gvForum.SelectedRow.FindControl("ModalPopupExtender1"));
ModalPopupExtender1.Show();
var gvForumDetail = (GridView)(gvForum.SelectedRow.FindControl("gvForumDetail"));
gvForumDetail.DataSource = ods;
gvForumDetail.DataBind();
}
protected void gvForumDetail_OnRowEditing(Object sender, GridViewEditEventArgs e)
{
var ModalPopupExtender1 = (ModalPopupExtender)(gvForum.SelectedRow.FindControl("ModalPopupExtender1"));
ModalPopupExtender1.Show();
var gvForumDetail = (GridView)(gvForum.SelectedRow.FindControl("gvForumDetail"));
gvForumDetail.EditIndex = e.NewEditIndex;
gvForumDetail.DataBind();
}
protected void gvForumDetail_CancelRecord(object sender, GridViewCancelEditEventArgs e)
{
var ModalPopupExtender1 = (ModalPopupExtender)(gvForum.SelectedRow.FindControl("ModalPopupExtender1"));
ModalPopupExtender1.Show();
var gvForumDetail = (GridView)(gvForum.SelectedRow.FindControl("gvForumDetail"));
gvForumDetail.EditIndex = -1;
gvForumDetail.DataBind();
}
I will try to answer part of your question, updating and deleting the code. you need to take advantage of the "onrowcommand" for the inner gridview (OnRowCommand).

Trying to Add Insert Row to Footer in GridView ASP.net

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();
}
}
}

Categories