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()
Related
I've written some code in the Page_PreRender event that gets the value of a DropDownList control and then performs some conditional logic. Problem is, the logic must not be very good.
The first If.. Then.. Else.. structure is working fine, however, if the selectedItem is not "Todos" (portuguese for "all") all the rows' visibility will be set to false. The issue seems to arise when the If SelectedItem <> "Todos" Then condition is met.
So, every option in the DropDownList aside from "Todos" sets the visibility of all rows to False instead of setting the visibility of the ones that don't match the SelectedItem to False.
Protected Sub Page_PreRender(sender As Object, e As EventArgs) Handles Me.PreRender
'Getting the selected item
Dim SelectedItem As String = CType(GridView1.HeaderRow.Cells(3).FindControl("DropDownList1"), DropDownList).SelectedItem.Text
If SelectedItem <> "Todos" Then
'This is the part where the issue seems to be located.
For Each Row As GridViewRow In GridView1.Rows
'Get the Text value
Dim depar As String = Row.Cells(3).Text
'If its different from the SelectedItem then the row's visible property should be set to false, if it's a match, set it to true.
If depar <> SelectedItem Then
Row.Visible = False
ElseIf depar = SelectedItem Then
Row.Visible = True
End If
Next
'If "Todos" was selected, all rows should be visible
ElseIf SelectedItem = "Todos" Then
'Make all rows visible
For Each row As GridViewRow In GridView1.Rows
row.Visible = True
Next
End If
End Sub
Code of GridView:
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataSourceID="SqlDataSource1" PageSize="20" Width="100%" >
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:CheckBox ID="CheckBox1" runat="server" />
<asp:LinkButton ID="LinkButton1" runat="server" CommandArgument='<%#CType(Container, GridViewRow).DataItem("IdPedido") %>' OnClick="LinkButton1_Click" OnCommand="LinkButton1_Command">Ver</asp:LinkButton>
</ItemTemplate>
<HeaderStyle Width="40px" />
</asp:TemplateField>
<asp:BoundField DataField="Observacoes" HeaderText="Assunto" SortExpression="Observacoes" />
<asp:BoundField DataField="NomeHotel" HeaderText="Hotel" SortExpression="NomeHotel" />
<asp:TemplateField HeaderText="Departamento" SortExpression="NomeDepartamento">
<HeaderTemplate>
Departamento<br />
<asp:DropDownList ID="DropDownList1" runat="server" AppendDataBoundItems="True" DataSourceID="SqlDataSource1" DataTextField="NomeDepartamento" DataValueField="IdDepartamento" AutoPostBack="True" OnLoad="DropDownList1_Load" OnSelectedIndexChanged="DropDownList1_SelectedIndexChanged">
<asp:ListItem>Todos</asp:ListItem>
</asp:DropDownList>
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:EnotelSuporteConnectionString1 %>" SelectCommand="SELECT [NomeDepartamento], [IdDepartamento] FROM [Departamentos]"></asp:SqlDataSource>
</HeaderTemplate>
<EditItemTemplate>
<asp:TextBox ID="TextBox1" runat="server" Text='<%# Bind("NomeDepartamento") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%# Bind("NomeDepartamento") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="DataPedido" HeaderText="Data" DataFormatString = "{0:dd, MMM yyyy}" SortExpression="DataPedido" />
<asp:BoundField DataField="DataFinalizado" HeaderText="Finalizado a" DataFormatString = "{0:dd, MMM yyyy}" SortExpression="DataFinalizado" />
<asp:BoundField DataField="Nome" HeaderText="Nome" SortExpression="Nome" />
<asp:BoundField DataField="Estado" HeaderText="Estado" SortExpression="Estado" Visible="False" />
<asp:BoundField DataField="IdPedido" HeaderText="IdPedido" InsertVisible="False" ReadOnly="True" SortExpression="IdPedido" Visible="False" />
</Columns>
</asp:GridView>
THe problem in your Row.Cells(3).Text is that you are defining the ItemTemplate in your gridview with Label and to get the ItemTemplates value you have to first find the control and then get the value from that control.
If you want the value of the label then use the following code to get the value,
Label label = (Label)Row.Cells(3).FindControl("Label1");
if(label != null)
string depar = label.Text;
NOTE
Code is in the c# you might want to convert it to the VB.
I created a simple Grid view with Multiple columns and add a button so when clicked pass the values of the row to a different webform but button on click not firing. I use the example code from the link
: http://msdn.microsoft.com/en-us/library/bb907626(v=vs.100).aspx
And this is my code:
<asp:GridView ID="GridView1" runat="server" AllowPaging="True"
AllowSorting="True" DataSourceID="SqlDataSource1"
PageSize="100" AutoGenerateColumns="False">
<Columns>
<%--<asp:HyperLinkField HeaderText="Edit" NavigateUrl="FormReport2.aspx"
Text="Edit" />--%>
<asp:TemplateField>
<ItemTemplate>
<asp:Button ID="AddButton" runat="server"
CommandName="AddToCart"
CommandArgument="<%# CType(Container,GridViewRow).RowIndex %>"
Text="Add to Cart" />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="fldEmployeeID" HeaderText="EmployeeID"
SortExpression="fldEmployeeID" />
<asp:BoundField DataField="fldAbsentDate" HeaderText="AbsentDate"
SortExpression="fldAbsentDate" />
<asp:BoundField DataField="fldAbsentCode" HeaderText="AbsentCode"
SortExpression="fldAbsentCode" />
<asp:BoundField DataField="fldRuleViolationWarningType"
HeaderText="Rule Violation Warning Type"
SortExpression="fldRuleViolationWarningType" />
<asp:BoundField DataField="fldRuleViolationIssueDate"
HeaderText="Rule Violation Issue Date"
SortExpression="fldRuleViolationIssueDate" />
<asp:BoundField DataField="fldLOAEndDate" HeaderText="LOA End Date"
SortExpression="fldLOAEndDate" />
</Columns>
</asp:GridView>
code behind
Protected Sub GridView1_RowCommand(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewCommandEventArgs)
If (e.CommandName = "AddToCart") Then
' Retrieve the row index stored in the CommandArgument property.
Dim index As Integer = Convert.ToInt32(e.CommandArgument)
' Retrieve the row that contains the button
' from the Rows collection.
Dim row As GridViewRow = GridView1.Rows(index)
' Add code here to add the item to the shopping cart.
End If
End Sub
Any help would be very appreciated. And also what would be the best way to pass the values from the row to a different web form from the code behind?
You forgot to sing up for the event. See the last line here:
<asp:GridView ID="GridView1" runat="server" AllowPaging="True"
AllowSorting="True" DataSourceID="SqlDataSource1"
PageSize="100" AutoGenerateColumns="False"
OnRowCommand="GridView1_RowCommand">
I have a gridview. Which consisits of two checkbox item templates.
<asp:GridView ID="GridView2" runat="server" AutoGenerateColumns="False"
CellPadding="4" ForeColor="#333333" GridLines="None"
<Columns>
<asp:BoundField DataField="student_name" HeaderText="Student Name" SortExpression="student_name" >
<ItemStyle HorizontalAlign="Center"></ItemStyle>
</asp:BoundField>
<asp:BoundField DataField="student_id"
HeaderText="Student ID" ItemStyle-HorizontalAlign="Center"
SortExpression="student_id" ReadOnly="True" >
<ItemStyle HorizontalAlign="Center"></ItemStyle>
</asp:BoundField>
<asp:TemplateField HeaderText="Practical Test">
<ItemTemplate>
<asp:CheckBox AutoPostBack="false" Checked="true" Id="CheckBoxTheory" runat="server" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Theory Test">
<ItemTemplate>
<asp:CheckBox AutoPostBack="false" Checked="true" Id="CheckBoxPractical" runat="server" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
When checking any one of the checkbox of a row of grid view ,i wants to make check the other checkbox automatically..and vice versa.. how is it possible?
On server side you need to change the checkbox so it has AutoPostBack="True" and add a OnCheckedChanged="CheckBoxTheory_Checked" so that the system can postback when you select it.
Then you can use something along the lines of:
Sub CheckBoxTheory_Checked (sender as object, e as eventargs)
Dim CheckBoxTheory as CheckBox = sender
Dim gvRow as GridviewRow = DirectCast(CheckBoxTheory.NamingContainer, GridviewRow)
Dim CheckBoxPractical as CheckBox = gvRow.FindControl("CheckBoxPractical")
If CheckBoxTheory.Checked = True Then
CheckBoxPractical.Checked = True
Else
CheckBoxPractical.Checked = False
End If
End Sub
This would get the sender as the checkbox, get the parent container (or NamingContainer), which would be a GridviewRow and then find the CheckBoxPractical control and then check if against the other checkbox value.
This is a long winded way of doing it but is the simplest at explaining the method.
I have set up a GridView as set out below. You can see there are four LinkButton's per row. What I want to do is make certain LinkButtons available depending on which row they appear in.
<asp:GridView ID="FormsGrid" runat="server" Width="657px" Height="250px" DataKeyNames="FORM_NAME,FORM_ACCESS,STATUS,ID"
AutoGenerateColumns="False" DataSourceID="SqlDataSource1" >
<Columns>
<asp:BoundField DataField="DEADLINE_DATE" HeaderText="Date" DataFormatString="{0:d}"
SortExpression="DEADLINE_DATE" />
<asp:BoundField DataField="FORM_NAME" HeaderText="Event"
SortExpression="FORM_NAME" >
<ItemStyle Width="240px" />
</asp:BoundField>
<asp:BoundField DataField="COMPULSORY" HeaderText="Compulsory?"
SortExpression="COMPULSORY" />
<asp:BoundField DataField="FORM_NO" HeaderText="Form"
SortExpression="FORM_NO" />
<asp:TemplateField HeaderText="Access">
<ItemTemplate>
<asp:LinkButton ID="FormLinkBtn" runat="server"
onclick="FormLinkBtn_Click">Form Link</asp:LinkButton>
<br />
<asp:LinkButton ID="NotReqBtn" runat="server"
onclick="NotReqBtn_Click">Not Required</asp:LinkButton>
<br />
<asp:LinkButton ID="DnLoadBtn" runat="server"
onclick="DnLoadBtn_Click">Download Pdf</asp:LinkButton>
<br />
<asp:LinkButton ID="UploadBtn" runat="server"
onclick="UploadBtn_Click">Upload Pdf</asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="STATUS" HeaderText="Completed?"
SortExpression="STATUS" />
<asp:BoundField DataField="ID" HeaderText="ID" SortExpression="ID" Visible="False" />
</Columns>
</asp:GridView>
When I try to make them not visible use the code below in FormsGrid_RowDataBound, it doesn't work and a get a null value error.
if e.Row.Cells(4).Text = "1" then
Dim FLbtn As LinkButton = FormsGrid.FindControl("FormLinkBtn")
FLbtn.Visible = True
Dim NRbtn As LinkButton = FormsGrid.FindControl("NotReqBtn")
NRbtn.Visible = False
Dim DLbtn As LinkButton = FormsGrid.FindControl("DnLoadBtn")
DLbtn.Visible = False
Dim ULbtn As LinkButton = FormsGrid.FindControl("UploadBtn")
ULbtn.Visible = False
end if
Also when I click say the FormLinkBtn, how do I determine the value of the fields in that particualr row?
Suggestion #1:
wrap your "if" statement in an "if" that checks for a row type:
if (e.Row.RowType == DataControlRowType.DataRow)
{
......// your code here
}
You getting null value exception becuase first you hit the header row. There are few types of rows.
You are only interested in DataRow in this case.
On question part 2:
if you go with just a link buttons and click events you will need to pass some data in CommandArgument or CommandName properties of the linkButton. You can use CommandField or ButtonField instead to avoid dealing with passing data identifying the row in CommandArgument or CommandName.
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.