ASP GridView DropdownList EDIT/UPDATE - asp.net

I have a GridView on a ASP-Page binding to a table with foreign-keys, where the Columns have DropdownLists with TEXT gathering to the VALUES, in other Tables.
When I EDIT the Row of the GridView, I add the Text of the Dropdowns in CodeBehind. This is all working fine. But when UPDATING I am trying to set the UpdateParameters of the DataSource manually, so i want to check which values in DropDowns are selected. But in every event i tried, the dropdowns are NULL.
I have tried:
RowUpdating- and RowEditing-Events of the GridView
Updating-Event of the DataSource
ASPX:
<asp:GridView ID="GridView1" runat="server" OnRowDataBound="GridView1_RowDataBound" AutoGenerateColumns="False" OnRowUpdating="GridView1_RowUpdating" OnRowEditing="GridView1_RowEditing" DataSourceID="SqlDataSource1" CellPadding="4" ForeColor="#333333" GridLines="None" AllowPaging="True" AllowSorting="True" Width="90%" DataKeyNames="id" Font-Size="Large">
<Columns>
<asp:TemplateField HeaderText="id" InsertVisible="False" SortExpression="id" Visible="False">
<EditItemTemplate>
<asp:Label ID="LabelIDe" runat="server" Text='<%# Eval("id") %>'></asp:Label>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="LabelIDi" runat="server" Text='<%# Bind("id") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Mitglied" InsertVisible="False" SortExpression="mitgliedid">
<EditItemTemplate>
<asp:Label ID="LabelMe" runat="server" Text='<%# Bind("mitgliedid") %>' Visible="false"></asp:Label>
<asp:DropDownList runat="server" ID="mitgliederDD">
</asp:DropDownList>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="LabelMi" runat="server" Text='<%# Bind("mitgliedid") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Amt" InsertVisible="False" SortExpression="amtid">
<EditItemTemplate>
<asp:Label ID="LabelAe" runat="server" Text='<%# Bind("amtid") %>' Visible="false"></asp:Label>
<asp:DropDownList runat="server" ID="ämterDD">
</asp:DropDownList>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="LabelAi" runat="server" Text='<%# Bind("amtid") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:CommandField ShowDeleteButton="True" ShowEditButton="True" ShowSelectButton="True" ItemStyle-HorizontalAlign="Right" />
</Columns>
<EditRowStyle BackColor="#7C6F57" HorizontalAlign="Center"></EditRowStyle>
<FooterStyle BackColor="#1C5E55" BorderStyle="None" Font-Bold="True" ForeColor="White"></FooterStyle>
<HeaderStyle BackColor="#666666" Font-Bold="True" ForeColor="White" CssClass="gridHeader"></HeaderStyle>
<PagerStyle BackColor="#666666" ForeColor="White" HorizontalAlign="Center" CssClass="gridPager" Font-Bold="True"></PagerStyle>
<RowStyle BackColor="#E3EAEB" HorizontalAlign="Center"></RowStyle>
<SelectedRowStyle BackColor="#C5BBAF" Font-Bold="True" ForeColor="#333333"></SelectedRowStyle>
<SortedAscendingCellStyle BackColor="#F8FAFA"></SortedAscendingCellStyle>
<SortedAscendingHeaderStyle BackColor="#246B61"></SortedAscendingHeaderStyle>
<SortedDescendingCellStyle BackColor="#D4DFE1"></SortedDescendingCellStyle>
<SortedDescendingHeaderStyle BackColor="#15524A"></SortedDescendingHeaderStyle>
<EmptyDataTemplate>Zur Zeit kein Datensatz in dieser Tabelle !</EmptyDataTemplate>
</asp:GridView>
<asp:SqlDataSource runat="server" ID="SqlDataSource1" OnUpdating="SqlDataSource1_Updating" ConnectionString='<%$ ConnectionStrings:ConnectionStringAPPDATA %>' SelectCommand="SELECT [id], [amtid], [mitgliedid] FROM [aemter_mitglieder]" DeleteCommand="DELETE FROM [aemter_mitglieder] WHERE [id] = #id" InsertCommand="INSERT INTO [aemter_mitglieder] ([amtid], [mitgliedid]) VALUES (#amtid, #mitgliedid)" UpdateCommand="UPDATE [aemter_mitglieder] SET [amtid] = #amtid, [mitgliedid] = #mitgliedid WHERE [id] = #id">
<DeleteParameters>
<asp:Parameter Name="id" Type="Int32"></asp:Parameter>
</DeleteParameters>
<InsertParameters>
<asp:Parameter Name="amtid" Type="Int32"></asp:Parameter>
<asp:Parameter Name="mitgliedid" Type="Int32"></asp:Parameter>
</InsertParameters>
<UpdateParameters>
<asp:Parameter Name="amtid" Type="Int32"></asp:Parameter>
<asp:Parameter Name="mitgliedid" Type="Int32"></asp:Parameter>
<asp:Parameter Name="id" Type="Int32"></asp:Parameter>
</UpdateParameters>
</asp:SqlDataSource>
**
CODE BEHIND:
**
protected void SqlDataSource1_Updating(object sender, SqlDataSourceCommandEventArgs e)
{
DropDownList ämterDD = (DropDownList)GridView1.FindControl("ämterDD");
DropDownList mitgliederDD = (DropDownList)GridView1.FindControl("mitgliederDD");
if(mitgliederDD != null && ämterDD != null)
{
SqlDataSource2.UpdateParameters["amtid"].DefaultValue = ämterDD.SelectedValue;
SqlDataSource2.UpdateParameters["mitgliedid"].DefaultValue = mitgliederDD.SelectedValue;
}
}
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
DropDownList ämterDD = (DropDownList)((GridView)sender).FindControl("ämterDD");
DropDownList mitgliederDD = (DropDownList)((GridView)sender).FindControl("mitgliederDD");
if (ämterDD != null && mitgliederDD != null)
{
SqlDataSource2.UpdateParameters["amtid"].DefaultValue = ämterDD.SelectedValue;
SqlDataSource2.UpdateParameters["mitgliedid"].DefaultValue = mitgliederDD.SelectedValue;
}
}
protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
{
DropDownList ämterDD = (DropDownList)((GridView)sender).FindControl("ämterDD");
DropDownList mitgliederDD = (DropDownList)((GridView)sender).FindControl("mitgliederDD");
if(ämterDD != null && mitgliederDD != null)
{
SqlDataSource2.UpdateParameters["amtid"].DefaultValue = ämterDD.SelectedValue;
SqlDataSource2.UpdateParameters["mitgliedid"].DefaultValue = mitgliederDD.SelectedValue;
}
}
Can anyone help me how i can set update-parameters of the GridView in code behind ?!

This code will help you to update your grid view data.
protected void GridView1_RowUpdating(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow && gridView.EditIndex == e.Row.RowIndex)
{
DropDownList ddlämter = (DropDownList)e.Row.FindControl("ddlämter");
Label LabelAe = (Label)e.Row.FindControl("LabelAe");
string strValue = Convert.ToString(LabelAe.Text);
// Bind Your Drop down Here
ddlämter.DataSource = ds;
ddlämter.DataTextField = "dbRequestType";
ddlämter.DataValueField = "dbID";
ddlämter.DataBind();
ddlämter.Items.Insert(0, new ListItem("--Choose--", "0"));
if (strValue != null && strValue != "")
ddlämter .Items.FindByValue(strValue).Selected = true;
}
}
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
DropDownList ddlämter = DropDownList)gvDeliverable.Rows[e.RowIndex].FindControl("ämterDD");
SqlDataSource2.UpdateParameters["amtid"].DefaultValue = Convert.ToInt32(ddlämter.SelectedValue);
}

Related

Get values from GridView and place it in text boxes

I just want to get the cell values from my GridView and place it in the different textboxes. I tried so many things but I just couldn't get it to work. Maybe you could help. Thanks.
This is the last thing I tried:
<asp:GridView ID="GridView1" runat="server" BackColor="#DEBA84" BorderColor="#DEBA84" BorderStyle="Solid" BorderWidth="1px" CellPadding="3" CellSpacing="2" AutoGenerateColumns="False" AutoGenerateSelectButton="True" onselectedindexchanged="GridView1_SelectedIndexChanged" OnSelectedIndexChanging="Gridview1_SelectedIndexChanging">
<Columns>
<asp:TemplateField ItemStyle-Width = "30px" HeaderText="Employee ID">
<ItemTemplate>
<asp:Label ID="lblEmpID" runat="server" Text='<%# Eval("emp_id") %>'></asp:Label>
</ItemTemplate>
<ItemStyle Width="30px"></ItemStyle>
</asp:TemplateField>
<asp:TemplateField HeaderText="Name">
<ItemTemplate>
<asp:Label ID="Label2" runat="server" Text='<%# Eval("emp_name") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Address">
<ItemTemplate>
<asp:Label ID="Label3" runat="server" Text='<%# Eval("emp_add") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Contact Num.">
<ItemTemplate>
<asp:Label ID="Label4" runat="server" Text='<%# Eval("emp_contact") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Hire Date">
<ItemTemplate>
<asp:Label ID="Label5" runat="server" Text='<%# Eval("hire_date") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Branch ">
<ItemTemplate>
<asp:Label ID="Label6" runat="server" Text='<%# Eval("hire_date") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
<FooterStyle BackColor="#F7DFB5" ForeColor="#8C4510" />
<HeaderStyle BackColor="#A55129" Font-Bold="True" ForeColor="White" />
<PagerStyle ForeColor="#8C4510" HorizontalAlign="Center" />
<RowStyle BackColor="#FFF7E7" ForeColor="#8C4510" />
<SelectedRowStyle BackColor="#738A9C" Font-Bold="True" ForeColor="White" />
<SortedAscendingCellStyle BackColor="#FFF1D4" />
<SortedAscendingHeaderStyle BackColor="#B95C30" />
<SortedDescendingCellStyle BackColor="#F1E5CE" />
<SortedDescendingHeaderStyle BackColor="#93451F" />
</asp:GridView>
Code Behind:
protected void btnUpdate_Click(object sender, EventArgs e)
{
EmployeeDLL edll = new EmployeeDLL();
edll.Update_Employee(txtEmpID.Text, txtName.Text, txtAddress.Text, txtContact.Text, txtHireDate.Text, txtBranchID.Text);
lblStatus.Text = "Record has been updated.";
edll = null;
}
protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
{
// txtEmpID.Text = GridView1.SelectedValue.ToString();
GridViewRow row = GridView1.SelectedRow;
txtEmpID.Text = row.Cells[0].Text;
txtName.Text = row.Cells[1].Text;
}
Use something like this
TextBox TextBoxLot = (TextBox)GridView1.Rows[rowIndex].Cells[1].FindControl("label");
When using <asp:TemplateField>, the data is not inside Cell but is contained in the Control present inside the Cell.
So, There are two steps to read the value:
Access the Control inside Cell
Access the Value from Control in step 1
Example:
protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
{
GridViewRow row = GridView1.SelectedRow;
// Step 1: Access the Control inside Cell
Label lblEmpId = (Label)row.Cells[0].FindControl("lblEmpID");
// Step 2: Access the Value from Control in step 1
string value = lblEmpId.Text;
// Combine Step 1 & Step 2
string valueEmpID = ((Label)row.Cells[0].FindControl("lblEmpID")).Text;
string name = ((Label)row.Cells[0].FindControl("Label2")).Text;
}

delete selected rows from gridview on selecting option from a dropdownlist located outside the gridview

I have a dropdownlist and a gridview control. DropDownlist is outside the gridview.
Dropdownlist contains an option Delete.
Gridview contains checkbox so that rows can be selected.
here is the gridview code:
<asp:GridView ID="gvRefDetail" runat="server" CssClass="mGrid" AutoGenerateColumns="False"
PageSize="50" Font-Names="Segoe UI" Font-Size="10pt" Width="800" AllowPaging="true"
BackColor="White" BorderColor="Silver" EmptyDataText="No Record" BorderStyle="Double"
BorderWidth="1px" CellPadding="4">
<HeaderStyle BackColor="red" />
<RowStyle BackColor="White" ForeColor="#003399" />
<Columns>
<asp:TemplateField>
<HeaderTemplate>
<input id="Checkbox2" type="checkbox" onclick="CheckAll(this)" runat="server" /></HeaderTemplate>
<ItemTemplate>
<asp:CheckBox ID="CheckBox1" runat="server" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="NameofReferred">
<ItemStyle Wrap="true" HorizontalAlign="Left" />
<ItemTemplate>
<asp:Label ID="lbltext" runat="server" Text='<%#Bind("NameofReferred") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txttext" runat="server" Text='<%#Bind("NameofReferred")%>'></asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="CustomerName">
<ItemStyle Wrap="true" HorizontalAlign="Left" />
<ItemTemplate>
<asp:Label ID="lbltext" runat="server" Text='<%#Bind("CustomerName") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txttext" runat="server" Text='<%#Bind("CustomerName")%>'></asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
</Columns>
<PagerStyle BackColor="#006699" Font-Bold="True" ForeColor="White" HorizontalAlign="Center" />
<AlternatingRowStyle BackColor="#CCFFFF" />
<SelectedRowStyle BackColor="#009999" Font-Bold="True" ForeColor="#CCFF99" />
<HeaderStyle BackColor="White" Font-Bold="True" ForeColor="Gray" BorderColor="Gray" />
<SelectedRowStyle BackColor="#009999" Font-Bold="True" ForeColor="#CCFF99" />
<HeaderStyle Font-Bold="True" ForeColor="White" />
</asp:GridView>
c# code:
protected void ddlaction_SelectedIndexChanged(object sender, EventArgs e)
{
if (ddlaction.SelectedValue == "1")
{
GridViewRow gvrow = gvRefDetail.SelectedRow;
int id = Convert.ToInt32(gvrow.Cells[1].Text);
string delref = "delete from tbl_Refferal where ID='" + id + "' ";
con = new SqlConnection(conString);
con.Open();
SqlCommand cmd2 = new SqlCommand(delref, con);
int temp1 = cmd2.ExecuteNonQuery();
con.Close();
BindRef();
}
}
Now, my question is when I select a one or more rows from gridview and select the delete option from dropdownlist, the selected rows must get deleted.
How can I do this?
Code On ddlaction_SelectedIndexChanged and stringVariableContainCheckboxvalues is string variable fetch from gridview checkbox selected in format ('1,3,5,6')
if (ddlaction.SelectedValue == "1")
{
string delref = "delete from tbl_Refferal where ID in (#checkboxSelectedValues)";
con = new SqlConnection(conString);
SqlCommand cmd2 = new SqlCommand(delref, con);
cmd2.Parameters.AddWithValue("#checkboxSelectedValues", stringVariableContainCheckboxvalues);
con.Open();
int temp1 = cmd2.ExecuteNonQuery();
con.Close();
BindRef();
}
Fetch Multiple Checkbox values:
foreach (GridViewRow row in gvRefDetail.Rows)
{
CheckBox cb = (CheckBox)row.FindControl("CheckBox1");
if (cb != null && cb.Checked)
{
// fetch values in string
}
}

Paging in child grid view not working

Hi all I am doing a program with a nested gridview my design is as follows
<asp:Panel CssClass="grid" ID="pnlCust" runat="server">
<asp:UpdatePanel ID="pnlUpdate" runat="server">
<ContentTemplate>
<asp:GridView AllowPaging="True" ID="gvCustomers" AutoGenerateColumns="False" DataKeyNames="EmpID"
runat="server" ShowHeader="true" BackColor="White" BorderColor="#DEDFDE" BorderStyle="None"
BorderWidth="1px" CellPadding="4" ForeColor="Black" GridLines="Vertical" >
<AlternatingRowStyle BackColor="White" />
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:Panel CssClass="group" ID="pnlCustomer" runat="server">
<%--<asp:Image ID="imgCollapsible" CssClass="first" ImageUrl="~/Assets/img/plus.png"
Style="margin-right: 5px;" runat="server" /><span class="header">
<%#Eval("EmpID")%>
:
<%#Eval("empname")%>--%>
<asp:RadioButton ID="rdbtn" runat="server" onclick="RadioCheck(this);" OnCheckedChanged="radio_changed" Text='<%# Bind("EmpID") %>'
AutoPostBack="true"></asp:RadioButton>
</asp:Panel>
<asp:Panel Style="margin-left: 20px; margin-right: 20px" ID="pnlOrders" runat="server">
<asp:GridView AutoGenerateColumns="false" CssClass="grid" ID="gvOrders" runat="server"
PageSize="1" ShowHeader="true" EnableViewState="false" DataKeyNames="EmpID" AllowPaging="true"
OnPageIndexChanging="gvOrders_PageIndexChanging">
<RowStyle CssClass="row" />
<AlternatingRowStyle CssClass="altrow" />
<Columns>
<asp:BoundField HeaderText="Employee Id" DataField="EmpID">
<ItemStyle HorizontalAlign="Center" Width="100px" />
</asp:BoundField>
<asp:TemplateField ItemStyle-CssClass="rownum">
<ItemTemplate>
<%# Container.DataItemIndex + 1 %>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderStyle-BackColor="#EFF1F1" ItemStyle-HorizontalAlign="Center"
ItemStyle-Height="25" HeaderStyle-Width="50" ItemStyle-Width="50">
<HeaderTemplate>
<input id="chkBoxAll" type="checkbox" onclick="checkAllBoxes()" />
</HeaderTemplate>
<ItemTemplate>
<asp:CheckBox ID="chkBoxChild" runat="server" />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="PayPeriodNumber" HeaderText="PayPeriod" HeaderStyle-BackColor="#EFF1F1"
ItemStyle-HorizontalAlign="Center" HeaderStyle-Width="80" ItemStyle-Width="80">
</asp:BoundField>
<asp:BoundField DataField="PayRollYear" HeaderText="Payroll Year" HeaderStyle-BackColor="#EFF1F1"
ItemStyle-HorizontalAlign="Center" HeaderStyle-Width="100" ItemStyle-Width="100">
</asp:BoundField>
<asp:BoundField DataField="PaymentDate" HeaderText="Payment Date" HeaderStyle-BackColor="#EFF1F1"
ItemStyle-HorizontalAlign="Center" HeaderStyle-Width="110" ItemStyle-Width="110">
</asp:BoundField>
</Columns>
</asp:GridView>
</asp:Panel>
</ItemTemplate>
</asp:TemplateField>
</Columns>
<FooterStyle BackColor="#CCCC99" />
<HeaderStyle BackColor="#6B696B" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="#F7F7DE" ForeColor="Black" HorizontalAlign="Right" />
<RowStyle BackColor="#F7F7DE" />
<SelectedRowStyle BackColor="#CE5D5A" Font-Bold="True" ForeColor="White" />
<SortedAscendingCellStyle BackColor="#FBFBF2" />
<SortedAscendingHeaderStyle BackColor="#848384" />
<SortedDescendingCellStyle BackColor="#EAEAD3" />
<SortedDescendingHeaderStyle BackColor="#575357" />
</asp:GridView>
</ContentTemplate>
</asp:UpdatePanel>
</asp:Panel>
Image of that on Page load
On selecting one of the radio buttons I will show the corresponding Employee details which is as follows
I have written paging for gridview as follows
if (!Page.IsPostBack)
{
GridViewChildPageIndex();
}
private void GridViewChildPageIndex()
{
DataTable dtPageIndex = new DataTable();
dtPageIndex.Columns.Add("PageIndex", typeof(int));
for (int i = 0; i < gvCustomers.Rows.Count; i++)
{
dtPageIndex.Rows.Add("0");
}
Session["ChildPageIndex"] = dtPageIndex;
}
Paging code of child gridview is as follows
protected void gvOrders_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
GridView gvwChild = (GridView)sender;
//GridViewRow gvRowParent = ((System.Web.UI.WebControls.GridView)sender).Parent as GridViewRow;
GridViewRow gvRowParent = gvwChild.Parent as GridViewRow;
gvwChild.PageIndex = e.NewPageIndex;
if (Session["ChildPageIndex"] != null)
{
DataTable dtPageIndex = (DataTable)Session["ChildPageIndex"];
dtPageIndex.Rows[gvRowParent.RowIndex][1] = e.NewPageIndex; // *I am getting error here as Object reference not set to an Object can any one tell where I went wrong*
}
BindChildGrdView(gvCustomers.DataKeys[gvRowParent.RowIndex].Value.ToString(), gvwChild);
}
Stack Trace
at _Default.gvOrders_PageIndexChanging(Object sender, GridViewPageEventArgs e) in d:\Projects\GridView-Collapsible\GridView-Collapsible\Default.aspx.cs:line 54
at System.Web.UI.WebControls.GridView.OnPageIndexChanging(GridViewPageEventArgs e)
at System.Web.UI.WebControls.GridView.HandlePage(Int32 newPage)
at System.Web.UI.WebControls.GridView.HandleEvent(EventArgs e, Boolean causesValidation, String validationGroup)
at System.Web.UI.WebControls.GridView.RaisePostBackEvent(String eventArgument)
at System.Web.UI.WebControls.GridView.System.Web.UI.IPostBackEventHandler.RaisePostBackEvent(String eventArgument)
at System.Web.UI.Page.RaisePostBackEvent(IPostBackEventHandler sourceControl, String eventArgument)
at System.Web.UI.Page.RaisePostBackEvent(NameValueCollection postData)
at System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint)
This may help you out:
In the gvOrders_PageIndexChanging function, use
GridViewRow gvRowParent = gvwChild.Parent.Parent as GridViewRow;
And inside the if condition
if (Session["ChildPageIndex"] != null)
{
DataTable dtPageIndex = (DataTable)Session["ChildPageIndex"];
dtPageIndex.Rows[gvRowParent.RowIndex][0] = e.NewPageIndex; // *I am getting error here as Object reference not set to an Object can any one tell where I went wrong*
}
And also could you debug and check if gvRowParent is an instantiated object in the second line of this function.

ASP.net GridView not Inserting from FooterTemplate

I'm stuck. I implemented all steps needed to insert new DB values from a checkbox and textbox controls in a GridView FooterTemplate into a SQLDataSource, but when I click my "Add" button to fire the Insert command, my page flashes and no insert occurs. As far as the actual SQL is concerned, I have a stored procedure set to the GridView's DataSource's insert action. I have separately tested the procedure and it works fine.
I based my design on this article: http://www.aspdotnetfaq.com/Faq/How-to-insert-row-in-GridView-with-SqlDataSource.aspx My error is probably somewhere in my event handlers. Any idea what I'm missing?
It would be too long to post all of the GridView code, so here are the essentials:
FooterTemplate for insert button:
<asp:GridView ID="CartonGridView" runat="server" AutoGenerateColumns="False"
CellPadding="6" DataKeyNames="CartonID" Width="100%"
DataSourceID="Carton_Table" ForeColor="#333333"
GridLines="None" AllowSorting="True">
<RowStyle BackColor="#F7F6F3" ForeColor="#333333" />
<Columns>
<asp:TemplateField ShowHeader="False">
<EditItemTemplate>
<asp:Button ID="Button1" runat="server" CausesValidation="True"
CommandName="Update" Text="Update" />
<asp:Button ID="Button2" runat="server" CausesValidation="False"
CommandName="Cancel" Text="Cancel" />
</EditItemTemplate>
<ItemTemplate>
<asp:Button ID="Button1" runat="server" CausesValidation="False"
CommandName="Edit" Text="Edit" />
</ItemTemplate>
<FooterTemplate>
<asp:Button ID="Button1" runat="server" CausesValidation="True"
CommandName="Insert" Text="Add" />
<asp:Button ID="Button2" runat="server" CausesValidation="False"
CommandName="Cancel" Text="Cancel" />
</FooterTemplate>
</asp:TemplateField>
...
SQLDataSource Binding to Gridview:
<asp:SqlDataSource ID="Carton_Table" runat="server"
ConnectionString="<%$ ConnectionStrings:DBConnectionString %>"
InsertCommand="spCartonInsert" InsertCommandType="StoredProcedure"
SelectCommand="spCartonSelect" SelectCommandType="StoredProcedure"
UpdateCommand="spCartonUpdate" UpdateCommandType="StoredProcedure">
...
<InsertParameters>
<asp:Parameter Name="Active" Type="Boolean" />
<asp:Parameter Name="Value" Type="String" />
<asp:Parameter Name="Description" Type="String" />
</InsertParameters>
Insertion Event Handlers:
protected void CartonGridView_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "Insert")
{
CheckBox Active = CartonGridView.FooterRow.FindControl("InsertActive") as CheckBox;
TextBox SAPCode = CartonGridView.FooterRow.FindControl("InsertSAPCode") as TextBox;
TextBox Description = CartonGridView.FooterRow.FindControl("InsertDescription") as TextBox;
SqlParameter paramActive = new SqlParameter("#Active", SqlDbType.Bit);
paramActive.Direction = ParameterDirection.Input;
paramActive.Value = Active.Checked;
insertParameters.Add(paramActive);
SqlParameter paramValue = new SqlParameter("#Value", SqlDbType.NVarChar, 30);
paramValue.Direction = ParameterDirection.Input;
paramValue.Value = paramValue.Text;
insertParameters.Add(paramValue);
SqlParameter paramDescription = new SqlParameter("#SAP_Long_Description", SqlDbType.NVarChar, 250);
paramDescription.Direction = ParameterDirection.Input;
paramDescription.Value = Description.Text;
insertParameters.Add(paramDescription);
Carton_Table.Insert();
}
}
protected void Carton_Table_Inserting(object sender, SqlDataSourceCommandEventArgs e)
{
e.Command.Parameters.Clear();
foreach (SqlParameter p in insertParameters)
e.Command.Parameters.Add(p);
}
Yep, the event-handler is not wired-up.
<asp:GridView ID="CartonGridView" runat="server" AutoGenerateColumns="False"
CellPadding="6" DataKeyNames="CartonID" Width="100%"
DataSourceID="Carton_Table" ForeColor="#333333"
GridLines="None" AllowSorting="True"
onrowcommand="CartonGridView_RowCommand">

Query regarding the nested grid views in asp.net/C#

I have defined a nested grid view in the following way.
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataSourceID="SqlDataSource1" OnRowDataBound="GridView1_RowDataBound" GridLines="None">
<Columns>
<asp:BoundField DataField="Date Of Transaction" HeaderText="Date Of Transaction"
SortExpression="Date Of Transaction" />
<asp:BoundField DataField="Invoice Number" HeaderText="Invoice Number" SortExpression="Invoice Number" />
<asp:BoundField DataField="totalAmount" HeaderText="totalAmount" ReadOnly="True"
SortExpression="totalAmount" />
<asp:TemplateField>
<ItemTemplate>
<asp:GridView ID="gridView2" runat="server" HorizontalAlign="Left" ShowHeader="false" GridLines="None" OnRowDataBound="gridView2_RowDataBound">
<Columns>
<asp:TemplateField ItemStyle-HorizontalAlign="Center" ItemStyle-Width="100px">
<ItemTemplate>
<asp:Button ID="Btn1" runat="server" Text="Download" OnClick="Btn1_Click"/>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:ComponentDBConnectionString %>"
SelectCommand="SelectUserPreviousHistory" SelectCommandType="StoredProcedure">
<SelectParameters>
<asp:Parameter DefaultValue="XYZZ" Name="userName" Type="String" />
</SelectParameters>
</asp:SqlDataSource>
The screenshot of the output is here. As you can see i have a "Download" button in each row of the child gridview (i.e., gridView2) but I want the download button to be last column but .net is rendering it to be the first column.
How can I do it?
More over gridview2 datasource is arraylist. Here is the code
gridView2.DataSource = titlesArrayList;
gridView2.DataBind();
Please help me
Thanks in anticipation
Why don't you simply add a Label before the Donwload-Button in the ItemTemplate? You could set the Label's Text in RowDataBound(gridView2_DataBound).
Edit: to show the header columns of the nested gridview in the header of the outer gridview, you could set ShowHeader="false" in the inner grid and use a HeaderTemplate with two labels for "Software Titles" and "Download here" and appropriate CSS-Styles to fit to the inner grid.
Edit:
Here is a working test-page. Pick the parts you didn't understand:
aspx:
<asp:GridView ID="GrdTransaction" runat="server" OnRowDataBound="GrdTransaction_RowDataBound" AutoGenerateColumns="false">
<Columns>
<asp:BoundField DataField="DateOfTransaction" HeaderText="Date Of Transaction"
SortExpression="DateOfTransaction" />
<asp:TemplateField>
<HeaderTemplate>
<table width="100%" cellspacing="0" cellpadding="0" border="0">
<tr>
<td><asp:Label ID="LblFileNameHeader" Text="File-Name" runat="server" /></td><td><asp:Label ID="LblDownloadHeader" Text="Download file" runat="server" /></td>
</tr>
</table>
</HeaderTemplate>
<ItemTemplate>
<asp:GridView ID="GrdDocument" runat="server" ShowHeader="false" GridLines="None" AutoGenerateColumns="false"
OnRowCommand="GrdDocument_RowCommand" OnRowDataBound="GrdDocument_RowDataBound">
<Columns>
<asp:TemplateField ItemStyle-HorizontalAlign="Center" ItemStyle-Width="100px">
<ItemTemplate>
<asp:Label ID="LblFileName" Text='<%# Eval("Doc")%>' runat="server" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField ItemStyle-HorizontalAlign="Center" ItemStyle-Width="100px">
<ItemTemplate>
<asp:Button ID="BtnDownload" runat="server" CommandArgument='<%# Eval("Doc")%>' CommandName="Download" Text="Download" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Codebehind(converted from vb.net to c#):
public class WebForm1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack) {
this.GrdTransaction.DataSource = GetOuterGridSource();
this.GrdTransaction.DataBind();
}
}
private DataTable GetOuterGridSource()
{
DataTable tbl = new DataTable();
tbl.Columns.Add(new DataColumn("ID", typeof(Int32)));
tbl.Columns.Add(new DataColumn("DateOfTransaction", typeof(DateTime)));
DataRow row = tbl.NewRow();
row["ID"] = 1;
row["DateOfTransaction"] = System.DateTime.Now;
tbl.Rows.Add(row);
row = tbl.NewRow();
row["ID"] = 2;
row["DateOfTransaction"] = System.DateTime.Now;
tbl.Rows.Add(row);
row = tbl.NewRow();
row["ID"] = 2;
row["DateOfTransaction"] = System.DateTime.Now;
tbl.Rows.Add(row);
return tbl;
}
private DataTable GetNestedGridSource()
{
DataTable tbl = new DataTable();
tbl.Columns.Add(new DataColumn("ID", typeof(Int32)));
tbl.Columns.Add(new DataColumn("Doc", typeof(string)));
DataRow row = tbl.NewRow();
row["ID"] = 1;
row["Doc"] = "Smart Defrag";
tbl.Rows.Add(row);
row = tbl.NewRow();
row["ID"] = 2;
row["Doc"] = "Visio Viewer";
tbl.Rows.Add(row);
row = tbl.NewRow();
row["ID"] = 2;
row["Doc"] = "Rapid Typing";
tbl.Rows.Add(row);
return tbl;
}
protected void GrdTransaction_RowDataBound(object sender, System.Web.UI.WebControls.GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow) {
dynamic row = ((DataRowView)e.Row.DataItem).Row;
dynamic GrdDocument = (GridView)e.Row.FindControl("GrdDocument");
GrdDocument.DataSource = GetNestedGridSource();
GrdDocument.DataBind();
GrdDocument.RowCommand += GrdDocument_RowCommand;
}
}
protected void GrdDocument_RowDataBound(object sender, System.Web.UI.WebControls.GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow) {
dynamic row = ((DataRowView)e.Row.DataItem).Row;
dynamic LblFileName = (Label)e.Row.FindControl("LblFileName");
LblFileName.Text = row("Doc").ToString;
}
}
protected void GrdDocument_RowCommand(object sender, System.Web.UI.WebControls.GridViewCommandEventArgs e)
{
if (e.CommandName == "Download") {
dynamic docName = e.CommandArgument.ToString();
}
}
public WebForm1()
{
Load += Page_Load;
}
}
I have set the LblFileName's Text poperty in GrdDocument_RowDataBound. That is redundant because i've always used eval on the aspx-page. I wanted to show both ways for the sake of completeness.
This is result:
in your gridView2, set AutoGenerateColumns="False" and add a asp:BoundField before the asp:TemplateField
Are you sure there is no missing code in your snippet?
<asp:GridView ID="gridView2" runat="server" HorizontalAlign="Left" ShowHeader="false" GridLines="None" OnRowDataBound="gridView2_RowDataBound" AutoGenerateColumns="False">
<Columns>
<asp:BoundField HeaderText="" DataField="ToString" />
<asp:TemplateField ItemStyle-HorizontalAlign="Center" ItemStyle-Width="100px">
<ItemTemplate>
<asp:Button ID="Btn1" runat="server" Text="Download" OnClick="Btn1_Click"/>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>

Resources