Query regarding binding the label in gridview ItemTemplate to String - asp.net

I have a nested gridview lets call parent gridview as gridview1 and child gridview as gridview2.
For each parent gridview's (gridview1) row i'm adding child gridview (gridview2) depending upon the invoice number that is present on that particular row in the gridview1. Here is a screen shot of that output here.
Inside the child gridview (i.e., gridview2) i have a download linkbutton which i add through item template and software title which i databind to gridview2 after filtering the output that i get through List<>. But as you can see the download linkbutton is being rendered first and then software titles next. But i want the software titles to be rendered first and download link button as last column in child gridview (i.e., gridview2).
Here is the code in .aspx page for nested gridviews. I got a suggestion from a fellow member of this forum that I can add label before the download link button and associate it with data source. I just could n't understand it. How can one do that ?
<asp:GridView ID="UserTransactionGridView" runat="server" AutoGenerateColumns="False"
DataSourceID="SqlDataSource1" OnRowDataBound="UserTransactionGridView_RowDataBound"
HorizontalAlign="Center" AllowPaging="true">
<Columns>
<asp:BoundField DataField="Date Of Transaction" HeaderText="Date Of Transaction"
SortExpression="Date Of Transaction" ItemStyle-HorizontalAlign="Center" />
<asp:BoundField DataField="Invoice Number" HeaderText="Invoice Number" SortExpression="Invoice Number"
ItemStyle-HorizontalAlign="Center" />
<asp:BoundField DataField="totalAmount" HeaderText="Total Amount" ReadOnly="True"
SortExpression="totalAmount" ItemStyle-HorizontalAlign="Center" />
<asp:TemplateField>
<HeaderTemplate>
<asp:Label Text="Software Title" ID="softwareLbl" runat="server"></asp:Label>
</HeaderTemplate>
<ItemTemplate>
<asp:GridView ID="gridView2" runat="server" HorizontalAlign="Left" GridLines="None"
ShowHeader="false">
<Columns>
<asp:TemplateField ItemStyle-HorizontalAlign="Center" ItemStyle-Width="100px">
<ItemTemplate>
<asp:LinkButton ID="DownloadLbtn" Text="Download" runat="server" OnClick="DownloadLbtn_Click"></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:componentConnString %>"
SelectCommand="SelectUserPreviousHistory" SelectCommandType="StoredProcedure">
<SelectParameters>
<asp:Parameter DefaultValue="xyz" Name="userName" Type="String" />
</SelectParameters>
</asp:SqlDataSource>
By the way here is the code where i'm binding child gridview with datasource (which is arraylist that i filter based on the invoice number present on the parent gridview (i.e., gridview1)).
protected void UserTransactionGridView_RowDataBound(Object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
GridView gridView2 = (GridView)e.Row.FindControl("gridView2");
System.Data.DataRowView dr = (System.Data.DataRowView)e.Row.DataItem;
gridView2.AutoGenerateColumns = true;
String x = dr[1].ToString();
softwareTitlesList = SoftwareListRetrieve();
ArrayList titles = new ArrayList();
foreach (SoftwareTitles softwareTitle in softwareTitlesList)
{
if (softwareTitle.InvoiceNumber.Contains(x))
titles.Add(softwareTitle.SoftwareTitle);
}
gridView2.DataSource = titles;
gridView2.DataBind();
softwareTitlesList.Clear();
}
}
BTW I'm using Visual studio 2008, asp.net/c# and no LINQ in my web application project.
Please help me.
Thank you in anticipation
PS: If some one doesn't like this question u may delete it after getting answered rather than down voting or flagging it.

1: Add AutoGenerateColumns="false" to your gv2
2: <%#Container.DataItem %> just before linkbutton
<asp:GridView ID="gridView2" runat="server" HorizontalAlign="Left" GridLines="None" ShowHeader="false" AutoGenerateColumns="false">
<Columns>
<asp:TemplateField ItemStyle-HorizontalAlign="Center" ItemStyle-Width="100px">
<ItemTemplate>
<%#Container.DataItem %>
<asp:LinkButton ID="DownloadLbtn" Text="Download" runat="server" OnClick="DownloadLbtn_Click"></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
You can add a separate TemplateField instead of adding in same before the existing one but the you get the idea why it is showing next to linkbutton.

Related

Model binding to formview when Gridview Edit button is clicked

I have searched here and on google as well.Things are not working so I'm posting this.
I have two controls GridView and FormView.I am using Model binding in my project.
<asp:GridView ID="GridView1" runat="server" DataKeyNames="Id" ItemType="Sample.Shared.ViewModel.ProfileMasterView"
AutoGenerateColumns="false" SelectMethod="Select_GridView">
<Columns>
<asp:BoundField DataField="Name" HeaderText="Name" />
<asp:BoundField DataField="Designation" HeaderText="Designation" />
<asp:BoundField DataField="EmailAddress" HeaderText="EmailAddress" />
<asp:TemplateField HeaderText="Action">
<ItemTemplate>
<asp:Button ID="Edit_Profile" OnClick="btnEdit_OnClick" runat="server" Text="Edit" CommandArgument="<%# BindItem.Id %>" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<asp:FormView ID="fvProfile" runat="server" RenderOuterTable="False" ItemType="Sample.Shared.ViewModel.ProfileMasterView"
DefaultMode="Insert" InsertMethod="Insert_Profile" >
I want to open FormView in Edit mode , where in gridview i am sending id of that record.On button click i want to change formview mode by calling BLL method which takes that Id from button click and retrieved record displayed in form view in edit mode.
Please help me , how can i implement this or any other similar way using model binding only,
Thank you.
As no one seems to answer this.I have found work around and also proper method for doing,I will add the answer as i get time from work.
before
asp:Button ID="Edit_Profile" OnClick="btnEdit_OnClick" runat="server" Text="Edit" CommandArgument="<%# BindItem.Id %>"
asp:FormView ID="fvProfile" runat="server" RenderOuterTable="False" ItemType="Sample.Shared.ViewModel.ProfileMasterView"
DefaultMode="Insert" InsertMethod="Insert_Profile"
after
asp:Button ID="Edit_Profile" OnCommand="btnEdit_OnClick" runat="server" Text="Edit" CommandArgument="<%# BindItem.Id %>"
asp:FormView ID="fvProfile" runat="server" RenderOuterTable="False" ItemType="Sample.Shared.ViewModel.ProfileMasterView" SelectMethod="Get"
DefaultMode="Insert" InsertMethod="Insert_Profile"
protected void btnEdit_OnClick(object sender, CommandEventArgs e)
{
gId = Convert.ToInt32(e.CommandArgument.ToString());
fvProfile.ChangeMode(FormViewMode.Edit);
fvProfile.Visible = true;
GridView1.Visible = false;
fvProfile.DataBind();
}
public DAL2.Models.OfficialDocument Get()
{
if(gId == 0)
{
ChangeViewMode();
return null;
}
BLL.ManageOfficialDocument mod = new BLL.ManageOfficialDocument();
var od = mod.GetById(gFILES_ID);
return od;
}
private int gId;

Error rendered when updating Gridview, only occurs when boundfield readonly is set to true

I have a GridView that functions off an sqlDataSource, it allows inserting and updating data. However, after the data is inserted, the "UpdatedBY" should not be editable by the user. So I added a readonly property to that bound column and set it to true, which generates the following error upon attempting to edit/update a column: Must declare the scalar variable "#UpdateBY". Note: the error only occurs when I implement a readonly property onto the "UpdateBY" column. When removed, no error when updating the Grid, but I do not want the user to be able to modify the UpdateBY column
Hypertext:
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
DataKeyNames="Mode_ID" DataSourceID="SqlDataSource1"
AutoGenerateEditButton="True" AllowPaging="True" AllowSorting="True">
<Columns>
<asp:BoundField DataField="Mode_ID" HeaderText="Mode ID" SortExpression="Mode_ID" Visible="false" />
<asp:BoundField DataField="ShipMode" HeaderText="Ship Mode" SortExpression="ShipMode" />
<asp:TemplateField HeaderText="Active" SortExpression="Active">
<EditItemTemplate>
<asp:CheckBox ID="chkactive" runat="server" Checked='<%# Bind("Active") %>'></asp:CheckBox>
</EditItemTemplate>
<ItemTemplate>
<asp:CheckBox ID="CheckBox1" runat="server" Checked='<%# Bind("Active") %>'></asp:CheckBox>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="UpdateDate" HeaderText="Update Date" SortExpression="UpdateDate" />
<asp:BoundField DataField="UpdateBY" HeaderText="Update BY" SortExpression="UpdateBY" ReadOnly="true" />
</Columns>
</asp:GridView>
...the SQL data source:
<asp:SqlDataSource
ID="SqlDataSource1"
ConnectionString="<%$ ConnectionStrings:ShipperNotificationConnectionString %>"
SelectCommand="SELECT Mode_ID, ShipMode, Active, UpdateDate, UpdateBY FROM [ShipMode]"
UpdateCommand="UPDATE ShipMode SET ShipMode=#ShipMode,
Active=#Active,UpdateDate=#UpdateDate, UpdateBY=#UpdateBY
WHERE Mode_ID=#Mode_ID"
InsertCommand="INSERT ShipMode (ShipMode,Active,UpdateDate,UpdateBY)
VALUES (#ShipMode,#Active,#UpdateDate,#UpdateBY)"
runat="server"
/>
could I get some assistance as to what I'm missing / failing to understand please?
I belieave you are getting the error once you hit Update correct?
You should follow the approach described here
From what I understand, you want to restrict the user from changing the value of the "UpdatedBy" field since that will defeat the purpose of this field.
In you ASPX code you must set your GridView1 OnRowUpdating = GridView1_RowUpdating, here is the code-behind for that:
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
GridViewRow row = GridView1.Rows[GridView1.EditIndex];
// Put a debug point here to check if value of originalUpdatedBy = UpdatedBy of Edit row
string originalUpdatedBy= row.Cells[7].Text;
if(!string.IsNullOrEmpty(originalUpdatedBy))
{
SqlDataSource1.UpdateParameters.Add("#UpdateBy", originalUpdatedBy);
SqlDataSource1.Update();
}
}

Enabling /Disabling ButtonField of GridView using Checkbox

I have grid view
one column is ItemTemplate column which has Checkbox field.
Other 2 columns are Databound columns. One column is ButtonField which is of Button type.
I want this button to initially set to disabled mode
Once the Checkbox is checked it should be enabling that particular row button field. Could anyone help in this?
My sample try
.aspx file
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:Email_NotificationConnection %>"
SelectCommand="SELECT [Customer_Name] FROM [Customer]"></asp:SqlDataSource>
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
DataSourceID="SqlDataSource1" EnableModelValidation="True">
<Columns>
<asp:BoundField DataField="Customer_Name" HeaderText="Customer_Name"
SortExpression="Customer_Name" />
<asp:TemplateField>
<ItemTemplate>
<asp:CheckBox runat="server" ID="non_prod_all_select" OnCheckedChanged="CheckBox2_CheckedChanged1" />
</ItemTemplate>
<HeaderStyle Width="30px" /></asp:TemplateField>
<asp:ButtonField ButtonType="Button" CommandName="Edit" Text="Button" />
</Columns>
</asp:GridView>
.aspx.cs file
protected void CheckBox2_CheckedChanged1(Object sender, EventArgs e)
{
CheckBox chk = (CheckBox)sender;
GridViewRow gridrow = ((GridViewRow)(chk.Parent));
if (chk.Checked)
{
Button btn = (Button)(gridrow.FindControl("Button"));
btn.Enabled = true;
}
else
{
Button btn = (Button)(gridrow.FindControl("Button"));
btn.Enabled = false;
}
}
Try using the below code:
ASPX code for the GridView1:
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:Email_NotificationConnection %>"
SelectCommand="SELECT [Customer_Name] FROM [Customer]"></asp:SqlDataSource>
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
DataSourceID="SqlDataSource1" EnableModelValidation="True">
<Columns>
<asp:BoundField DataField="Customer_Name" HeaderText="Customer_Name"
SortExpression="Customer_Name" />
<asp:TemplateField>
<ItemTemplate>
<asp:CheckBox runat="server" AutoPostBack="true" ID="non_prod_all_select" OnCheckedChanged="CheckBox2_CheckedChanged1" />
</ItemTemplate>
<HeaderStyle Width="30px" /></asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:Button ID="Button1" runat="server" Text="Button" Enabled="false" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Code Behind (for CheckBox Check Changed Event handler):
protected void CheckBox2_CheckedChanged1(object sender, EventArgs e)
{
foreach (GridViewRow row in GridView3.Rows)
{
((Button)row.FindControl("Button1")).Enabled = ((CheckBox)row.FindControl("non_prod_all_select")).Checked;
}
}
Changes made:
1.Set AutoPostBack for CheckBox to true.
2.Removed Button Field and added a template field with button in the third column of the Grid (so that the asp:Button control could be read easily in code behind)
3.Changed the code behind code to do the necessary.
NOTE: I have checked this code locally and is working as expected. So just replace your old code with this and let me know in case of any issues.

How to delete a row in a dynamically generating grid view?

Hello Respected sirs,
I am generating a shopping cart like ordering system, in which i add/bind the productname, productprice, and productquantity from DataTable to GridView.
I have Added an ImageButton to the gridview only for deleting the selected row.
I also know that we can not delete a row from a dynamically generated grid view. so i placed a code in the ImageButton Click event that deletes the row from DataTable (Which is STATIC during the whole process) and again binds the Data With GridView.
Please note that i hv already once bind the data with gridview in my "BTN_ADD TO CART_Clicked".
Here is my code snippet,
protected void gvorderlist_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "Delete")
{
int index = Convert.ToInt32(e.CommandArgument);
DataRow row = dt.Rows[index];
dt.Rows.Remove(row);
gvorderlist.DataSource = dt;
gvorderlist.DataBind();
}
}
and ASP code is,
<asp:GridView ID="gvorderlist" runat="server" CellPadding="4"
ForeColor="#333333" GridLines="None" AllowPaging="True" PageSize="5"
onpageindexchanging="gvorderlist_PageIndexChanging"
onrowcommand="gvorderlist_RowCommand">
<AlternatingRowStyle BackColor="White" />
<Columns>
<asp:TemplateField HeaderText="Cancel Order" ShowHeader="False">
<ItemTemplate>
<asp:ImageButton ID="ImgbtnCancelOrder" runat="server" CausesValidation="false"
ImageUrl="~/images/cross.PNG" OnClientClick="Javascript: return confirm('Aap Chutiye hai');" CommandName="Delete"
CommandArgument="<%# ((GridViewRow) Container).RowIndex %>"/>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
I am getting an Error which says : The GridView 'gvorderlist' fired event RowDeleting which wasn't handled.
Any help will be appreciated...
Thank You
The error explains everything. You need todefine the event method for OnRowDeleting in markup:
<asp:GridView ID="gvorderlist" runat="server" CellPadding="4"
ForeColor="#333333" GridLines="None" AllowPaging="True" PageSize="5"
onpageindexchanging="gvorderlist_PageIndexChanging"
onrowcommand="gvorderlist_RowCommand" OnRowDeleting="gvorderlist_RowDeleting">
<AlternatingRowStyle BackColor="White" />
<Columns>
<asp:TemplateField HeaderText="Cancel Order" ShowHeader="False">
<ItemTemplate>
<asp:ImageButton ID="ImgbtnCancelOrder" runat="server" CausesValidation="false"
ImageUrl="~/images/cross.PNG" OnClientClick="Javascript: return confirm('Aap Chutiye hai');" CommandName="Delete"
CommandArgument="<%# ((GridViewRow) Container).RowIndex %>"/>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
And add an empty method in the code:
protected void gvorderlist_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
// No need to implement code here
}
The attributes for the GridView are case-sensitive, so change onrowcommand to OnRowCommand and see if that fires when you click the delete button. If not, you'll need to define OnRowDeleting explicitly. (Also change the capitalization of onpageindexingchange)
Give Command Name=D instead of Delete. It searches for Row_Deleting event when Command Name =Delete.

Use LINQ with GridView

I am new to web dev and using controls so please forgive me.
I have a GridView with check boxes in it (please see markup below)
When a user goes through and checks any boxes and hits my submit button
I want to run LINQ query to get all the rows with the checkbox1.checked = True
Something like:
Dim sList = (From row in Gridview1
Where row.Cells("IsStarFleet") = True
row.Cells("ID)).ToList
Markup:
<asp:GridView ID="GridView1" runat="server" Width="516px" AutoGenerateColumns="False" AllowPaging="True">
<Columns>
<asp:BoundField DataField="ID" HeaderText="ID" />
<asp:BoundField DataField="FirstName" HeaderText="FirstName" />
<asp:TemplateField HeaderText="IsStarFleet">
<ItemTemplate>
<asp:CheckBox ID="CheckBox1" runat="server" AutoPostBack ="False" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
You need to use FindControl for controls in a TemplateField and Cells(index) for BoundFields:
Dim checkedIDs = From row In GridView1.Rows.Cast(Of GridViewRow)()
Where DirectCast(row.FindControl("CheckBox1"), CheckBox).Checked
Select row.Cells(0).Text
Dim checkedIdList = checkedIDs.ToList()

Resources