Linking SqlDataSource to label for a single item in ASP.NET - 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>

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?

losing the first result of retrieved data when binding it to repeater control

I am developing a social network in which i must show a list of friends to the current user.
i am using SqlDataReader to retrieve data from database then bind it by a repeater , the problem is that the repeater always skip the first result so it only shows the n-1 results out of n. anybody can explain to me this behaviour?
my code is:
string cmdstr2 = "SELECT students.fname, students.lname,students.username FROM students INNER JOIN friends ON students.username = friends.tostudent WHERE (friends.fromstudent ='" + cuser + "')";
SqlCommand cmd2 = new SqlCommand(cmdstr2, sc);
SqlDataReader rd = cmd2.ExecuteReader();
if (rd.Read())
{
Repeater1.DataSource = rd;
Repeater1.DataBind();
}
in the design view, i have written this code to include the repeater in the page:
<asp:Repeater ID="Repeater1" runat="server">
<HeaderTemplate>
<div style="font-size:xx-large;">
الأصدقاء</div>
</HeaderTemplate>
<ItemTemplate>
<div style="font-size:x-large; color:Black; margin-right:0px; margin-top:0px;">
<asp:HyperLink ID="HyperLink1" runat="server"
NavigateUrl='<%# "student.aspx?user="+DataBinder.Eval(Container.DataItem,"username")%>' >
<%#DataBinder.Eval(Container.DataItem, "fname")%> <%#DataBinder.Eval(Container.DataItem, "lname")%>
</asp:HyperLink>
</div>
</ItemTemplate>
<FooterTemplate>
</FooterTemplate>
</asp:Repeater>
Your rd.Read() in your if statement is advancing it 1 record
Try using:
if (rd.HasRows)

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

How do I extract the value of a label on gridview?

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;

Populate DropdownList based upon other DropDownList VB

I have found a couple of examples on the internet to do this but really struggling to get it working in VB. (Tried a converter but had mixed results)
I need the selection options of a Dropdownlist to be populated based upon the differing values in the first dropdown list.
Can anyone help with a releativley simple example in VB? Not fussed if the values are "hard coded" in the script. Or a SQL bit that pulls the data from a table
Thanks in advance!
The way it is done is to populate second dropdown in SelectedIndexChanged event of the first dropdown
Example:
Protected Sub ddlCountry_SelectedIndexChanged(ByVal sender As Object, ByVal e As EventArgs)
Dim CountryID As Integer = Convert.ToInt32(ddlCountry.SelectedValue.ToString())
FillStates(CountryID)
End Sub
Private Sub FillStates(ByVal countryID As Integer)
Dim strConn As String = ConfigurationManager.ConnectionStrings("DatabaseConnectionString").ConnectionString
Dim con As New SqlConnection(strConn)
Dim cmd As New SqlCommand()
cmd.Connection = con
cmd.CommandType = CommandType.Text
cmd.CommandText = "Select StateID, State from State where CountryID =#CountryID"
cmd.Parameters.AddWithValue("#CountryID", countryID)
Dim objDs As New DataSet()
Dim dAdapter As New SqlDataAdapter()
dAdapter.SelectCommand = cmd
con.Open()
dAdapter.Fill(objDs)
con.Close()
If objDs.Tables(0).Rows.Count > 0 Then
ddlState.DataSource = objDs.Tables(0)
ddlState.DataTextField = "State"
ddlState.DataValueField = "StateID"
ddlState.DataBind()
ddlState.Items.Insert(0, "--Select--")
Else
lblMsg.Text = "No states found"
End If
End Sub
With html source as so:
<asp:DropDownList ID="ddlState" runat="server" AutoPostBack="True">
</asp:DropDownList>
<asp:DropDownList ID="ddlCountry" runat="server"
AutoPostBack="True" OnSelectedIndexChanged="ddlCountry_SelectedIndexChanged">
</asp:DropDownList>
You could accomplish this declaratively in the ASPX page like this:
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:myConnString %>" SelectCommand="SELECT id, name FROM planets"></asp:SqlDataSource>
<asp:DropDownList ID="ddlPlanets" AutoPostBack="true" DataTextField="name" DataValueField="id" DataSourceID="SqlDataSource1" runat="server" AppendDataBoundItems="true" />
<asp:SqlDataSource ID="SqlDataSource2" runat="server" ConnectionString="<%$ ConnectionStrings:myConnString %>" SelectCommand="SELECT planetid, name FROM moons" FilterExpression="planetid = '{0}'">
<FilterParameters>
<asp:ControlParameter Name="planetid" ControlID="ddlPlanets" PropertyName="SelectedValue" />
</FilterParameters>
</asp:SqlDataSource>
<asp:DropDownList ID="ddlMoons" DataTextField="name" DataValueField="planetid" DataSourceID="SqlDataSource2" runat="server" />
Your best option will be to capture the SelectedIndexChanged event on the first dropdownlist, examine what the current value of that dropdownlist is, and then use that to clear and then populate the items in the second dropdownlist. When you do so, remember to set the AutoPostBack property of the first DropDownList to "true".

Resources