How do I extract the value of a label on gridview? - asp.net

Does anyone know how I can extract the value of the label below?
<asp:TemplateField HeaderText="Event Dates">
<ItemTemplate>
<asp:Label ID="Label4" runat="server" Text='<%# Bind("eventDates","{0:MM/dd/yyyy}") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
I am querying the database and would like to use the label value on the WHERE clause.
For instance,
This isn't working:
Dim cmd As New SqlCommand("select * from mytable where username= #username and eventDate = #edate", myconn)
cmd.Parameters.AddWithValue("#username", username)
cmd.Parameters.AddWithValue("#edate", Label4.Text)
Thank you

You have to get the row first. Then from the row find the control
var label4 = (Label)row.FindControl("Label4");
var labelText = label4.text;

Related

Reloading drop down box in asp.net detailsview

In a detailsview I have a drop down list whose selection determines the list in a second Drop down list. When the web page loads all my "Get Data" Functions load the various Drop down boxes. After I make a selection in the first of the two related drop down boxes I call an "index changed" function that takes the value of the first drop down box, as a variable, and puts it into a SQL statement. This SQL statement runs correctly inside SQL. However, the second drop down doesn't reload with the new data the values in the second drop down remain the same. Here is the pertinent code:
` <asp:TemplateField HeaderText="Planting Hatchery">
<ItemTemplate>
<asp:Label ID="lblPlantHatch" runat="server" Text='<%# Eval ("HatcheryCodePlant")%>' Visible = "true"></asp:Label>
</ItemTemplate>
<insertItemTemplate>
<asp:DropDownList ID="ddPlantingHatchery" runat="server" DataSource='<%# GetPlantingHatchery()%>'DataTextField="HatcheryNamePlant" DataValueField="HatcheryCodePlant" width= "150" AppendDataBoundItems="true" AutoPostBack="true"
OnSelectedIndexChanged="ddPlantingHatchery_indexchanged">
<asp:ListItem Text="Select" Value="" />
</asp:DropDownList>
</insertItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Water Body Name">
<ItemTemplate>
<asp:Label ID="lblStreamName" runat="server" Text='<%# Eval("CatalogNo")%>' Visible = "true"></asp:Label>
</ItemTemplate>
<insertItemTemplate>
<asp:DropDownList ID="ddCatalogName" runat="server" DataSource='<%# GetCatalogNames()%>'
DataTextField="StreamName" DataValueField="CatalogNo" AppendDataBoundItems="true" >
<asp:ListItem Text="Select" Value="" />
</asp:DropDownList>
<asp:ObjectDataSource ID="dsWaterBody" runat="server" TypeName="StreamName"
<SelectMethod="GetCatalogNames">
<SelectParameters>
<asp:ControlParameter Name="HatcheryCodePlant" Type="string" ControlID="ddPlantingHatchery" PropertyName="Selectedvalue"/>
</SelectParameters>
</asp:ObjectDataSource>
</insertItemTemplate>`
This is the Code Behind:`
Public Function GetPlantingHatchery() As DataSet
Dim myConnection As New SqlConnection(ConnectionString)
Dim ad As New SqlDataAdapter("SELECT HatcheryNamePlant, HatcheryCodePlant FROM HatcheryPlant Order by HatcheryNamePlant", myConnection)
Dim ds As New DataSet()
ad.Fill(ds, "HatcheryPlant")
Return ds
End Function
Public Function GetCatalogNames() As DataSet
Dim myConnection As New SqlConnection(ConnectionString)
Dim ad As New SqlDataAdapter("SELECT StreamName, CatalogNo, HatcheryNamePlant, HatcheryCodePlant, LLID FROM vwStockingWatersByHatchery Order By StreamName", myConnection)
Dim dsWaterBody As New DataSet()
ad.Fill(dsWaterBody, "Catalog")
Return dsWaterBody
End Function
Public Function ddPlantingHatchery_indexchanged(sender As Object, e As EventArgs)
Try
Dim ddCatNum As DropDownList = TryCast(dvSMasterCurrentYear.FindControl("ddCatalogName"), DropDownList)
'ddCatNum.SelectedValue = TryCast(dvSMasterCurrentYear.FindControl("ddPlantingHatchery"), DropDownList).SelectedValue
MySelectedValue = TryCast(dvSMasterCurrentYear.FindControl("ddPlantingHatchery"), DropDownList).SelectedValue
Dim myConnection As New SqlConnection(ConnectionString)
Dim ad As New SqlDataAdapter("SELECT StreamName, CatalogNo, HatcheryNamePlant, HatcheryCodePlant, LLID FROM vwStockingWatersByHatchery where HatcheryCodePlant = '" + MySelectedValue + "' Order By StreamName", myConnection)
Dim dsWaterBody As New DataSet()
ad.Fill(dsWaterBody, "Catalog")
Return dsWaterBody
Catch ex As Exception
End Try`
What do I need to do to load the second Drop down list with the new data?

Linking SqlDataSource to label for a single item in ASP.NET

I have a asp:SqlDataSource that returns a single row. How do I return that value into a label. I got it working in a asp:DataList but its overkill since its a single record.
<asp:SqlDataSource ID="SqlDataSource2" runat="server"
ConnectionString="<%$ ConnectionString %>"
SelectCommand="SELECT STATEMENT">
</asp:SqlDataSource>
<asp:DataList ID="DataList5" runat="server" DataSourceID="SqlDataSource2">
<ItemTemplate>
<asp:Label ID="label1" runat="server" Text='<%# Eval("ID") %>'></asp:Label><br />
</ItemTemplate>
</asp:DataList>
Here is one way to do it in C#:
DataView oDV = (System.Data.DataView)SqlDataSource2.Select(DataSourceSelectArguments.Empty);
Label1.Text = string.Join("|", oDV.Table.Rows[0].ItemArray.Select(p => p.ToString()).ToArray());
I guess my project is using an actual method instead of a property like I first suggested.
You could use a text SqlCommand(String, SqlConnection), passing the select statement and a SqlConnection(String) to your database.
public string GetSelectStatement()
{
SqlConnection conn = new SqlConnection(ConnectionString);
string selectStatement = "SELECT TOP 1 ID FROM Customer";
SqlCommand comm = new SqlCommand(selectStatement, conn);
comm.CommandType = System.Data.CommandType.Text;
SqlDataReader reader = comm.ExecuteReader();
// My code has a while, but you shouldn't need it with only one record
reader.Read();
string ID = (string)reader["ID"];
return ID;
}
Then in your page (aspx) or control (ascx) you can use that method to bind the label text
<asp:Label ID="label1" runat="server" Text='<%# GetSelectStatement() #>'></asp:Label>

How to reference a DataRow explicitly in the code behind and show/hide based on another DataRow value

In a DetailsView I have set visible = false for a TemplateField with HeaderText of "No Treatment Reason:".
In the code behind how can I reference the DataRow explicitly and make it visible based on the value of the other TemplateField with the HeaderText of "Care Plan Intent:" ?
<asp:DetailsView ID="dvTest" FooterStyle-Width="100%" Font-Bold="false" BackColor="#A2C4EA"
FieldHeaderStyle-Width="35%" BorderWidth="1" CellSpacing="2" Font-Names="Arial, Helvetica, sans-serif"
Font-Size="12px" runat="server" AutoGenerateRows="False" AllowPaging="False" style="width:98%"
HeaderStyle-BackColor="White" HeaderStyle-Font-Bold="true" HeaderStyle-HorizontalAlign="center">
<Fields>
<asp:TemplateField HeaderText="Care Plan Intent:">
<ItemTemplate>
<asp:Label skinid="tablabelblack" id="lblIntent" runat="server" Text='<%# Eval("CarePlanIntent") %>' />
<asp:HiddenField runat="server" ID="hidCarePlanIntent" Value='<%# Eval("CarePlanIntent") %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="No Treatment Reason:" Visible="false">
<ItemTemplate>
<asp:Label skinid="tablabelblack" id="lblNoTreatmentReason" runat="server" Text='<%# Eval("NoTreatmentReason") %>' />
</ItemTemplate>
</asp:TemplateField>
</Fields>
</asp:DetailsView>
You have to use the DataBound event and cast the DataItem to the correct type (f.e. DataRowView). You can use FindControl to get your controls and following LINQ query to get the correct column to make it (in)visible:
protected void dvTest_DataBound(Object sender, EventArgs e)
{
var noTreatCol = this.dvTest.Fields.Cast<DataControlField>()
.First(field => field.HeaderText == "No Treatment Reason:");
DataRow row = ((DataRowView) dvTest.DataItem).Row;
Label tablabelblack = (Label)dvTest.FindControl("tablabelblack");
HiddenField hidCarePlanIntent = (HiddenField)dvTest.FindControl("hidCarePlanIntent");
string value = row.Field<string>("Value"); // just an example
noTreatCol.Visible = value == "SomeValueThatMakesItVisible";
}
Is it possible to do that in VB and without LINQ?
Of course:
Protected Sub dvTest_DataBound(sender As Object, e As EventArgs)
Dim row As DataRow = DirectCast(dvTest.DataItem, DataRowView).Row
Dim tablabelblack As Label = DirectCast(dvTest.FindControl("tablabelblack"), Label)
Dim hidCarePlanIntent As HiddenField = DirectCast(dvTest.FindControl("hidCarePlanIntent"), HiddenField)
Dim value As String = row.Field(Of String)("Value") ' just an example '
Dim noTreatColIndex As Int32 = -1
For i As Int32 = 0 To Me.dvTest.Fields.Count - 1
Dim field = dvTest.Fields(i)
If field.HeaderText = "No Treatment Reason:" Then
noTreatColIndex = i
Exit For
End If
Next
If noTreatColIndex > -1 Then
dvTest.Fields(noTreatColIndex).Visible = value = "SomeValueThatMakesItVisible"
End If
End Sub

GridView RowEditing event only fires on alternate rows

I have a GridView as below:
<asp:GridView ID="gvChain" runat="server" Font-Size="Small" CellPadding="3" CellSpacing="1" GridLines="None"
AutoGenerateColumns="False">
<HeaderStyle BackColor="#CCCCCC" />
<Columns>
<asp:TemplateField HeaderText="Department" ControlStyle-Width="175px">
<EditItemTemplate>
<asp:Label ID="lblDepartment" runat="server" Text='<%# Bind("Department") %>'></asp:Label>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="lblDepartment" runat="server" Text='<%# Bind("Department") %>'></asp:Label>
</ItemTemplate>
<ControlStyle Width="175px" />
</asp:TemplateField>
<asp:TemplateField HeaderText="Manager Level 1" ControlStyle-Width="175px">
<ItemTemplate>
<asp:Label ID="lblManager1" runat="server" Text=""></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:DropDownList ID="cbManager1" runat="server"></asp:DropDownList>
</EditItemTemplate>
<ControlStyle Width="175px" />
</asp:TemplateField>
<asp:TemplateField HeaderText="Manager Level 2" ControlStyle-Width="175px">
<ItemTemplate>
<asp:Label ID="lblManager2" runat="server" Text=""></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:DropDownList ID="cbManager2" runat="server"></asp:DropDownList>
</EditItemTemplate>
<ControlStyle Width="175px" />
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:LinkButton ID="btnEdit" CommandName="Edit" runat="server" Text="Edit" CssClass="buttonStyle" CausesValidation="false"/>
</ItemTemplate>
<EditItemTemplate>
<asp:LinkButton ID="btnSave" CommandName="Update" runat="server" Text="Save" CssClass="buttonStyle" CausesValidation="false"/>
<asp:LinkButton ID="btnCancel" CommandName="Cancel" runat="server" Text="Cancel" CssClass="buttonStyle" CausesValidation="false" />
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:LinkButton ID="btnDelete" CommandName="Delete" runat="server" Text="Delete" CssClass="buttonStyle" CausesValidation="false" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
The BoundField is populated in the Page_Load event as below:
Dim dHandler As DepartmentHandler = New DepartmentHandler
Dim depts As New List(Of Department)
depts = dHandler.GetDepartmentList
gvChain.DataSource = depts.
If Not Page.IsPostBack Then
gvChain.DataBind()
End If
Populating of the TemplateFields is then done in the RowDataBound event as below:
If e.Row.RowType = DataControlRowType.DataRow Then
If e.Row.RowState = DataControlRowState.Edit Then
Dim cbManager1 As DropDownList = TryCast(e.Row.FindControl("cbManager1"), DropDownList)
Dim cbManager2 As DropDownList = TryCast(e.Row.FindControl("cbManager2"), DropDownList)
Dim eHandler As EmployeeHandler = New EmployeeHandler
' Get the list of managers
Dim mgrs As New List(Of Manager)
mgrs = eHandler.GetManagerList
cbManager1.DataSource = mgrs
cbManager2.DataSource = mgrs
cbManager1.DataValueField = "Name"
cbManager1.DataTextField = "Name"
cbManager2.DataValueField = "Name"
cbManager2.DataValueField = "Name"
cbManager1.DataBind()
cbManager2.DataBind()
' Get the department name from the label in cell 0
Dim lbl As Label = e.Row.Cells(0).FindControl("lblDepartment")
Dim dept As Department = New Department
dept.Department = lbl.Text
' Pass the department name to the getManager1/2 functions to return the correct manager for that department
Dim mgr1 As Manager = eHandler.getManager1(dept)
Dim mgr2 As Manager = eHandler.getManager2(dept)
' Upper case the manager name to search the DDLs for item
Dim mgr1Name As String = mgr1.Name.ToUpper()
Dim mgr2Name As String = mgr2.Name.ToUpper()
' Find the manager in the DDL and select
cbManager1.SelectedValue = mgr1Name
cbManager2.SelectedValue = mgr2Name
Else
' If GV isnt in edit mode then populate labels in itemtemplate with manager 1 and 2 values
Dim lblManager1 As Label = DirectCast(e.Row.FindControl("lblManager1"), Label)
Dim lblManager2 As Label = DirectCast(e.Row.FindControl("lblManager2"), Label)
Dim eHandler As EmployeeHandler = New EmployeeHandler
Dim lbl As Label = e.Row.Cells(0).FindControl("lblDepartment")
Dim dept As Department = New Department
dept.Department = lbl.Text
Dim mgr1 As Manager = eHandler.getManager1(dept)
Dim mgr2 As Manager = eHandler.getManager2(dept)
lblManager1.Text = mgr1.Name
lblManager2.Text = mgr2.Name
End If
End If
I then have the below in the RowEditing event
gvChain.EditIndex = e.NewEditIndex
gvChain.DataBind()
When there is only 1 record displayed in the GridView, I click the edit button and the GridView goes into Edit mode I am able to update that record using the RowUpdating event and this works fine. However, if I add another record to the GridView, clicking on the edit button of that record gives a NullReference exception. If I then add another record, that 3rd record will go into edit mode. A 4th record will again fail with a NullReference exception and so on.
When debugging, it seems that on rows indexes 1,3,5 etc. the GridView doesn't go into edit mode however on row indexes 0, 2, 4 etc. the GridView will switch to edit mode.
This seems really strange behaviour. Any ideas what may be causing the GridView not to go into Edit mode on these rows?
A row's state can be one or a combination of the DataControlRowState values, so use bitwise operations to determine whether the state of the row includes a DataControlRowState value.
here
RowState contains more than one value (Alternate | Edit if you check RowState property during edit mode) using bit-logic.
Try
If (e.Row.RowState And DataControlRowState.Edit) > 0 Then
I got round this by amending the getDepartmentList function to return the Manager1 and Manager 2 fields then databinding them in the same was as I had bound 'Department'.
I then amended the RowDataBound event to the following:
If e.Row.RowType = DataControlRowType.DataRow Then
If e.Row.RowState And DataControlRowState.Edit Then
Dim cbManager1 As DropDownList = TryCast(e.Row.FindControl("cbManager1"), DropDownList)
Dim cbManager2 As DropDownList = TryCast(e.Row.FindControl("cbManager2"), DropDownList)
Dim eHandler As EmployeeHandler = New EmployeeHandler
' Get the list of managers
Dim mgrs As New List(Of Manager)
mgrs = eHandler.GetManagerList
cbManager1.DataSource = mgrs
cbManager2.DataSource = mgrs
cbManager1.DataValueField = "Name"
cbManager1.DataTextField = "Name"
cbManager2.DataValueField = "Name"
cbManager2.DataValueField = "Name"
cbManager1.DataBind()
cbManager2.DataBind()
' Get the department name from the label in cell 0
Dim lbl As Label = e.Row.Cells(0).FindControl("lblDepartment")
Dim dept As Department = New Department
dept.Department = lbl.Text
' Pass the department name to the getManager1/2 functions to return the correct manager for that department
Dim mgr1 As Manager = eHandler.getManager1(dept)
Dim mgr2 As Manager = eHandler.getManager2(dept)
' Upper case the manager name to search the DDLs for item
Dim mgr1Name As String = mgr1.Name.ToUpper()
Dim mgr2Name As String = mgr2.Name.ToUpper()
' Find the manager in the DDL and select
cbManager1.SelectedValue = mgr1Name
cbManager2.SelectedValue = mgr2Name
End If
End If

Dropdown list to populate checkboxes

My asp.net application currently uses a Telerik RadGrid to show product data. At the top of the page, I have a dropdown list that will include 4 different categories. Based on the user's selection of category, the checkboxes in the grid will either become checked or not checked. The website's 1500 products will always show in the grid, it's the checkboxes that will be changing.
Ex: Product 1 is in Category A, therefore if a user clicks on Category B in the dropdown, the checkbox next to Product 1 will be unchecked. The only way that will be checked is if the user changes the dropdown to view the products currently in Category A.
I am having trouble trying to figure out how to approach this. For one, the line if (ProductInMarket.Checked = true) throws an error sayingThe name ProductInMarket' does not exist in the current context.` The second problem I have is that I can't figure out how to finish the UpdateMarket method. That's what happens when you take a lunch in the middle of coding. :/
This is what I have so far and I would really appreciate some help here.
<asp:DropDownList ID="MarketDropDownList" runat="server" AutoPostBack="true" OnSelectedIndexChanged="MarketDropDownList_SelectedIndexChanged" AppendDataBoundItems="true">
</asp:DropDownList>
<telerik:GridTemplateColumn AllowFiltering="true" HeaderText="Product ID" UniqueName="productid" ReadOnly="true">
<HeaderTemplate>
<asp:CheckBox ID="headerCheck" runat="server" onClick="javascript:SelectDeselectAllCheckboxes(this);" />
</HeaderTemplate>
<ItemTemplate>
<asp:Checkbox ID="ProductInMarket" runat="server" />
<asp:HiddenField runat="server" ID="ProductID" />
</ItemTemplate>
</telerik:GridTemplateColumn>
private void UpdateMarket(string MarketID)
{
//add products to market when checked
if (ProductInMarket.Checked = true)
{
string strConn = ConfigurationManager.ConnectionStrings["DBConnectingString"].ToString();
using (SqlConnection con = new SqlConnection(strConn))
{
using (SqlCommand cmd = new SqlCommand())
{
cmd.Connection = con;
cmd.CommandType = CommandType.Text;
cmd.CommandText = "UPDATE table SET ProductID = #ProductID WHERE MarketID = #MarketID";
}
}
}
}
I would recommend using batch updating via Performing Batch Operations Using DataAdapters.
Note: The UpdateBatchSize property is the key here, because it tells ADO.NET how many items to send in each batch. Setting it to zero will force the batch to be as large as possible, setting it to 1 will basically make it ignore batching, because it will send one at a time. You will need to play with this value to get the optimal value, taking into account performance and memory-usage (larger batches will use up more memory until it is cleaned up).
<asp:DropDownList ID="MarketDropDownList" runat="server" AutoPostBack="true" OnSelectedIndexChanged="MarketDropDownList_SelectedIndexChanged" AppendDataBoundItems="true">
</asp:DropDownList>
<telerik:GridTemplateColumn AllowFiltering="true" HeaderText="Product ID" UniqueName="productid" ReadOnly="true">
<HeaderTemplate>
<asp:CheckBox ID="headerCheck" runat="server" onClick="javascript:SelectDeselectAllCheckboxes(this);" />
</HeaderTemplate>
<ItemTemplate>
<asp:Checkbox ID="ProductInMarket" runat="server" />
<asp:HiddenField runat="server" ID="ProductID" />
</ItemTemplate>
</telerik:GridTemplateColumn>
private void UpdateMarket(string MarketID)
{
//add products to market when checked
if (ProductInMarket.Checked = true)
{
string strConn = ConfigurationManager.ConnectionStrings["DBConnectingString"].ToString();
using (SqlConnection con = new SqlConnection(strConn))
{
using (SqlCommand cmd = new SqlCommand())
{
cmd.Connection = con;
cmd.CommandType = CommandType.Text;
cmd.CommandText = "UPDATE table SET ProductID = #ProductID WHERE MarketID = #MarketID";
}
}
}
}
try this
jsfiddle

Resources