Adding a ListItem to the top of a ListBox - asp.net

I have the ListBox below and would like to know how I would be able to add a ListItem to the ListBox which is not coming form the SQLDataSource. I want to add a Zero at the top of the this ListBox and then add the data coming from the SQLDataSource.
<asp:ListBox
ID="ListBox4"
runat="server"
DataSourceID="getAvaibleChapters"
DataTextField="chapterNo"
DataValueField="chapterNo"
Rows="1"
SelectedValue='<%# Bind("no") %>' />
<asp:SqlDataSource ID="getAvaibleChapters" runat="server"
ConnectionString="<%$ ConnectionStrings:RXIConnectionString %>"
SelectCommand="SELECT chapterNo FROM Chapters WHERE (subjectID = #subjectid) order by chapterNo asc">
<SelectParameters>
<asp:QueryStringParameter Name="subjectid" QueryStringField="subjectid" />
</SelectParameters>
</asp:SqlDataSource>

try like this .. it may help you .
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
DataRow dr = dt.NewRow();
dr.ItemArray = new object[] { 0, "---Select an item---" };
dt.Rows.InsertAt(dr,0);
cmbProName.DisplayMember = "ProductName";
cmbProName.ValueMember = "PID";
cmbProName.DataSource = dt;

I would change the DataSource SQL statement like something below
select 0, 'select all'
UNION
select chapterNo, no from Chapter
http://sqlfiddle.com/#!3/baad6/2

This is the best method of doing this,,
DECLARE #temp TABLE
(
chapterNo int
)
insert #temp
values (0);
INSERT INTO #temp
SELECT chapterNo FROM Chapters WHERE subjectID = #subjectid;
select * from #temp order by chapterNo asc

Related

ASP.NET Listbox Multiple Items passed to SQL Server then passed to Gridview

What I'm trying to do is to select multiple countries from listbox, then hit select, then a gridview would pull out data from a table based on the countries selected. my problem is that I don't know how to pass the string where country in (A,B,C,...) into a SQL Server stored procedure. Any advice on this would be great!
My listbox is
<asp:ListBox ID="Country" cssclass="LBox" runat="server" SelectionMode="Multiple">
<asp:ListItem Text="A" Value="A" />
<asp:ListItem Text="B" Value="B" />
<asp:ListItem Text="C" Value="C" />
<asp:ListItem Text="D" Value="D" />
..............
</asp:ListBox>
My select button is
Protected Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim li As ListItem
Dim myString As String = ""
Dim myString2 As String = ""
For Each li In ListBoxComp.Items
If li.Selected = True Then
If myString = "" Then
myString = "'" & li.Text & "'"
Else
myString = myString & ", " & "'" & li.Text & "'"
End If
End If
Next
myString2 = myString2
Session("Selected") = myString2
from
http://forums.asp.net/t/1618260.aspx?code+SQL+to+retrieve+records+from+multiple+random+selection+list+box
My gridview is
<asp:GridView ID="GridView1" runat="server"
AutoGenerateColumns="False" BackColor="White"
BorderColor="#999999" BorderStyle="Solid" BorderWidth="1px"
CellPadding="3" DataSourceID="SqlDataSource1" ForeColor="Black"
GridLines="Vertical">
......
</asp:GridView>
Datasource is
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:ConnectionString %>"
SelectCommand="usp_select" SelectCommandType="StoredProcedure">
<SelectParameters>
<asp:SessionParameter Name="myString2" SessionField="Selected" />
</SelectParameters>
</asp:SqlDataSource>
SQL Server stored procedure is
ALTER PROCEDURE [dbo].[usp_select]
#myString2 varchar(5000)
AS
BEGIN
SELECT *
FROM dbo.table
WHERE country IN (#myString2)
END
My problem is that I don't know how to pass the string where country in (A,B,C,...) into the SQL Server stored procedure. Any advice on this would be great!
In the example you got your code from, you must use dynamic sql in your stored proc. Something like:
Declare #sqlstring varchar(max);
Set #sqlstring = 'Select * from dbo.table where country in (' + #myString2 + ')';
Execute sp_executesql #sqlstring;
Otherwise you're trying to use IN with just a string, which is causing your problems I think.
But honestly, I stay away from dynamic sql when possible. You might consider finding a good split string function that turns your string into a table or cte. Then you could use these rows in a join or a "where exists" clause. I like to pass stuff like this in as xml and use an xml function to create a similar cte. A final alternative is to create a user-defined table type with just rows of strings and pass this into your stored proc from a datatable on the front end, but that's probably overkill.
You could try this:
Define an StrList data type in SQL Server:
USE [YourDB]
GO
CREATE TYPE [dbo].[StrList] AS TABLE(
[Value] [varchar](100) NULL
)
GO
Alter your stored procedure to accept that kind of parameter instead of the string:
ALTER PROCEDURE [dbo].[usp_select]
#countryList AS StrList READONLY
AS
BEGIN
SELECT *
FROM dbo.table
WHERE country IN (SELECT Value FROM #countryList)
END
Pass the country names as a StrList instead of a string. I am not sure how to do it with the SessionParameter, however. In code-behind, I do it like this:
Dim tbl As new DataTable()
tbl.Columns.Add("Value", System.Type.GetType("System.String"));
For Each li In ListBoxComp.Items
If li.Selected = True Then
tbl.Rows.Add(li.Text)
End If
Next
Dim prm As new SqlParameter("#countryList", SqlDbType.Structured)
prm.Direction = ParameterDirection.Input
prm.Value = tbl
I hope that this can give you some idea, and that my translation from C# to VB.NET is correct...

dropdown list display base on a radio button

I am an amature programmer. I have just start coding around one month
I am trying to write a code which shows the specific values of a database table in a dropdown list based on the radio button checked changed.
I tried to do it by using a session which saves the id of the table values and sends it to the drop down list, but nothing happens
<asp:RadioButton ID="rdbHome" runat="server" AutoPostBack="True"
GroupName="rdb" oncheckedchanged="rdbHome_CheckedChanged" />
<asp:DropDownList ID="DropDownList1" runat="server"
DataSourceID="SqlDataSource1" DataTextField="p" DataValueField="playerID">
</asp:DropDownList>
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:BasketballConnectionString %>"
SelectCommand="PlayerName" SelectCommandType="StoredProcedure">
<SelectParameters>
<asp:SessionParameter Name="team1ID" SessionField="team1" Type="Int32" />
</SelectParameters>
</asp:SqlDataSource>
protected void rdbHome_CheckedChanged(object sender, EventArgs e)
{
string conStr = WebConfigurationManager.ConnectionStrings["BasketballConnectionString"].ConnectionString;
SqlConnection con = new SqlConnection(conStr);
SqlCommand cmd = new SqlCommand("team1ID", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#mID", int.Parse(Request.QueryString["mID"]));
SqlCommand cmd2 = new SqlCommand("matchTeam2", con);
cmd2.CommandType = CommandType.StoredProcedure;
cmd2.Parameters.AddWithValue("#mID", int.Parse(Request.QueryString["mID"]));
try
{
con.Open();
SqlDataReader reader;
reader = cmd2.ExecuteReader();
//reader2 = cmd2.ExecuteReader();
reader.Read();
Session["team1"] = reader["team1ID"].ToString();
cmd.Parameters.AddWithValue("#team1ID", Session["team1"]);
}
catch(Exception ex)
{
lblMsg.Text = "خطا" + ex.Message;
}
}
ALTER PROCEDURE [dbo].[team1ID](#mID INT)
AS
BEGIN
SELECT teamTbl.teamID AS team1ID from
teamTbl join matchTbl ON matchTbl.team1ID=teamTbl.teamID
WHERE matchID=#mID
END
ALTER PROCEDURE [dbo].[matchTeam2](#mID int)
AS
BEGIN
SELECT t1.teamName as team1Name,t2.teamName as team2name,matchTbl.playeName,matchTbl.playerScore,
matchTbl.team1Score,matchTbl.team2Score,team1ID,team2ID
FROM matchTbl JOIN teamTbl as t1 on matchTbl.team1ID=t1.teamID
JOIN teamTbl as t2 on matchTbl.team2ID=t2.teamID
WHERE matchTbl.matchID=#mID
END
and the code for sqlDataSource
ALTER PROCEDURE [dbo].[PlayerName](#team1ID INT)
AS
BEGIN
SELECT playersTbl.playerName, playersTbl.playerID
FROM teamTbl JOIN playersTbl ON teamTbl.teamID=playersTbl.teamID
WHERE teamTbl.teamID=#team1ID
END
It seems that you are not populating the dropdown at all in this case. Inside 'rdbHome_CheckedChanged' method, you should be populating the 'DropDownList1' dropdown control.
Something like the following:
DropDownList1.Items.Add(new ListItem("5", "5%"));
thanks for your help guys, the code worked fine, there were only some silly mistakes in it, the above code is edited and has no problems

DropDownList with DataValueField and DataTextField asp.net C#

In my database, I entry CPVComID value from DropDownList (like
0,1,2,3) and display dataValueFiled value into DropDownList like
(-Select-, Conquest, CBC, Insight Management).
Error Message:
Exception Details: System.ArgumentOutOfRangeException: 'ddlCardCPVComName' has a SelectedValue which is invalid because itdoes not exist in the list of items. Parameter name: value
ASPX:
<asp:DropDownList ID="ddlCardCPVComName" runat="server" AppendDataBoundItems="True"
DataSourceID="SqlDSCPVCompanyName" DataTextField="CPVComName"
dataValueFiled="ddlCardCPVComName" Width="205px" DataValueField="CPVComID">
<asp:ListItem Value="0"> -SELECT- </asp:ListItem>
</asp:DropDownList>
<asp:SqlDataSource ID="SqlDSCPVCompanyName" runat="server"
ConnectionString="<%$ ConnectionStrings:OptimaWebCustomerQueryCon %>"
SelectCommand="SELECT CPVComID, CPVComName FROM DDCPVCompanyName ORDER BY CPVComID">
</asp:SqlDataSource>
Code Behind:
private void getReceeivedCPV()
{
using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["OptimaWebCustomerQueryCon"].ConnectionString))
{
conn.Open();
string str = #"SELECT CardCPVID, CardID,
CardCPVComName,
CardCPVSentDate, CardCPVStatus, CardCPVRcevDate, CPVRemarks FROM CC_CardCPV Where CardID LIKE '" + GVCPVReceived.SelectedValue + "'";
using (SqlCommand com = new SqlCommand(str, conn))
{
using (SqlDataReader dr = com.ExecuteReader())
{
if (dr.Read())
{
TextBox1.Text = Convert.ToString(dr[2]);
ddlCardCPVComName.SelectedValue = Convert.ToString(dr[2]);
txtCardCPVSentDate.Text = Convert.ToDateTime(dr[3]).ToString("dd MMM yyyy");
ddlCardCPVStatus.SelectedItem.Value = Convert.ToString(dr[4]);
if (dr[5] != DBNull.Value)
{
txtCardCPVRcevDate.Text = Convert.ToDateTime(dr[5]).ToString("dd MMM yyyy");
}
else
{
txtCardCPVRcevDate.Text = "";
}
txtCPVRemarks.Text = Convert.ToString(dr[6]);
}
}
}
conn.Close();
}
}
What should I do? Please suggest me.
I can describe why this exception arises..In the below line of code you are setting a value to the dropdownlist ddlCardCPVComName..
ddlCardCPVComName.SelectedValue = Convert.ToString(dr[2]);
Here the exception says that there is no such an item in the dropdownlist ddlCardCPVComName.So you must check when you bind the dropdownlist ddlCardCPVComName
that there exist the particular item which you are going to set..
Check this binding query and make sure that the desired items are bound to the datasource..
<asp:SqlDataSource ID="SqlDSCPVCompanyName" runat="server"
ConnectionString="<%$ ConnectionStrings:OptimaWebCustomerQueryCon %>"
SelectCommand="SELECT CPVComID, CPVComName FROM DDCPVCompanyName ORDER BY CPVComID">
</asp:SqlDataSource>
If am not wrong, Remove dataValueFiled="ddlCardCPVComName"(DropDown) from Your aspx code and execute.
I just change "dlCardCPVStatus.SelectedItem.Text = Convert.ToString(dr[4]);" and success to do this

select dropdownlist value and display gridview from different tables ASP.NET

I create web application. I add drop down list. I connect list with Names of Tables Categories. for example 1, 2, 3. When I select value 1 it should be created grid view populated with data from Table 1. When I select 2 create grid view populated with data from Table 2..
I connect tables in the SQL database. PrimaryKey Category ID, foreign key1, foreign key2 approprietly.
I know how to populate grid view by select value in the drop down list, but the values from one table. In this case I have 4 tables and I don't know how to realise that. Is there somebody who can help me? by some tutorial, or piece of code? thanks
try this...
aspx page:
<body>
<form runat="server">
<asp:DropDownList runat="server" ID="ddlDb" AutoPostBack="True" OnSelectedIndexChanged="ddlDb_SelectedIndexChanged">
<asp:ListItem Text="-- Select --" Value=""></asp:ListItem>
<asp:ListItem Text="Students" Value="Students"></asp:ListItem>
<asp:ListItem Text="Classes" Value="Classes"></asp:ListItem>
</asp:DropDownList>
<asp:GridView ID="GridView1" runat="server">
</asp:GridView>
</form>
</body>
aspx.cs:
protected void ddlDb_SelectedIndexChanged(object sender, EventArgs e)
{
if (!string.IsNullOrEmpty(ddlDb.SelectedValue))
{
var dbPath = Server.MapPath(#"\App_Data\Database1.mdf");
var scon = "Data Source=.\\SQLEXPRESS;AttachDbFilename='" + dbPath + "';Integrated Security=True;User Instance=True";
var cmd = "select * from " + ddlDb.SelectedValue;
var dt = new DataTable();
var da = new SqlDataAdapter(cmd, scon);
da.Fill(dt);
GridView1.DataSource = dt;
GridView1.DataBind();
}
}

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