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
Related
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
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
I have a comments box which has a template field which looks something like this..
<asp:GridView ID="GridView2" runat="server" AutoGenerateColumns="False" DataSourceID="CommentsDataSource" Height="167px" Width="325px">
<Columns>
<asp:TemplateField HeaderText="Comments">
<ItemTemplate>
<div style="background-color:Silver">
<div class="avatar-frame">
<asp:Image ID="ProfilePic" runat="server"/>
</div>
<h1><%# Eval("TagLine")%></h1>
<h2><%# Eval("IfNonMemberUserName")%></h2>
<p><%# Eval("CommentBody")%></p>
</div>
</ItemTemplate>
<AlternatingItemTemplate>
<div style="background-color:White">
<div class="avatar-frame">
</div>
<h1><%# Eval("TagLine")%></h1>
<h2><%# Eval("IfNonMemberUserName")%></h2>
<p><%# Eval("CommentBody")%></p>
</div>
</AlternatingItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<asp:SqlDataSource ID="CommentsDataSource" runat="server" ConnectionString="<%$ ConnectionStrings:BookMeetConnString %>" ProviderName="<%$ ConnectionStrings:BookMeetConnString.ProviderName %>" SelectCommand="SELECT [IfNonMemberUserName], [UserAvatar], [TagLine], [CommentBody] FROM [comments] WHERE ([BookID] = ?)">
<SelectParameters>
<asp:QueryStringParameter Name="?" QueryStringField="ID" />
</SelectParameters>
</asp:SqlDataSource>
Some background:
I have an MS Access database with a table called 'userprofiles' which has a field called AvatarURL. Similiarly there is also a table called 'comments' which has lookupfield called 'UserAvatar' inside of it referring to the 'userprofiles' table's 'AvatarURL' field.
I am receiving the "'ProfilePic' is not declared. It may not be accessible due to it's permission level" error in my code behind. Intellisense is telling me that the image that has the ID 'ProfilePic' is not declared (within the DisplayData sub routine.
The problematic bit of code is:
Protected Sub DisplayData()
Dim conn As OleDbConnection = New OleDbConnection(ConfigurationManager.ConnectionStrings("BookMeetConnString").ConnectionString)
Dim sql = "SELECT * FROM userprofiles WHERE TravellerName=#f1"
Dim cmd = New OleDbCommand(sql, conn)
cmd.Parameters.AddWithValue("#f1", User.Identity.Name)
conn.Open()
Dim profileDr = cmd.ExecuteReader()
profileDr.Read()
If Not IsDBNull(profileDr("AvatarURL")) Then ProfilePic.ImageUrl = profileDr.Item("AvatarURL")
conn.Close()
End Sub
At runtime, detail.aspx works fine, but the avatars in the comment box don't show up at all. What am I doing wrong?
EDIT:
I have managed to get this far:
Protected Sub GridView2_RowDataBound(sender As Object, e As GridViewRowEventArgs)
Dim conn As OleDbConnection = New OleDbConnection(ConfigurationManager.ConnectionStrings("BookMeetConnString").ConnectionString)
Dim sql = "SELECT * FROM userprofiles WHERE TravellerName=#f1"
Dim cmd = New OleDbCommand(sql, conn)
cmd.Parameters.AddWithValue("#f1", User.Identity.Name)
conn.Open()
Dim profileDr = cmd.ExecuteReader()
profileDr.Read()
Dim ProfilePic
If e.Row.RowType = DataControlRowType.DataRow Then
ProfilePic = e.Row.FindControl("ProfilePic")
If Not IsDBNull(profileDr("AvatarURL")) Then ProfilePic.ImageUrl = profileDr.Item("AvatarURL")
End If
conn.Close()
End Sub
However, the images still do not appear at runtime. What is wrong with this? Should I be using the datareader?
The only way to refer to get at ProfilePic is to set it at DataBind time. You'll need to wire up the GridView2_RowDataBound event by adding OnRowDataBound="GridView2_RowDataBound" to your asp:GridView tag.
You'll then get the RowDataBound event for each row (even header and footer rows, so you need to test for what type of row is currently firing the event. You can then use FindControl on the current row item to look for the current row's ProfilePic. You'll have to cast the output of that function into an Image.
protected void GridView2_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
Image ProfilePic = (Image)e.Row.FindControl("ProfilePic");
ProfilePic.ImageUrl = "stuff";
}
}
As a control within a template, you can only access the control when binding, in particular in the OnRowDataBound event handler (for a GridView).
In this event handler you need to call FindControl with the ID of the wanted control and cast it to the right type (only if you need to access specific members of that type).
Try this
public string DisplayData()
Dim conn As OleDbConnection = New OleDbConnection(ConfigurationManager.ConnectionStrings("BookMeetConnString").ConnectionString)
Dim sql = "SELECT * FROM userprofiles WHERE TravellerName=#f1"
Dim cmd = New OleDbCommand(sql, conn)
cmd.Parameters.AddWithValue("#f1", User.Identity.Name)
conn.Open()
Dim profileDr = cmd.ExecuteReader()
profileDr.Read()
string imagename= profileDr("AvatarURL")
conn.Close()
return imagename
End Sub
and client side change for
<asp:Image ID="ProfilePic" **ImageUrl='<%# DisplayData()%>'** runat="server" />
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();
}
}
How to put the first item on the DropDownList in blank ? In VB is something like, DropDownList.index[0] = "";
I did this:
string StrConn = ConfigurationManager.ConnectionStrings["connSql"].ConnectionString;
SqlConnection conn = new SqlConnection(StrConn);
conn.Open();
SqlDataReader dr;
string sql;
sql = #"Select Nome From DanielPessoas";
SqlCommand cmd = new SqlCommand(sql, conn);
dr = cmd.ExecuteReader();
DropDownList1.DataSource = dr;
DropDownList1.DataTextField = "Nome";
DropDownList1.DataValueField = "Nome";
DropDownList1.DataBind();
After your DataBind call, add this code.
DropDownList1.Items.Insert(0, new ListItem(string.Empty, string.Empty));
You can define the empty item in aspx file if you set AppendDataBoundItems property to true.
<asp:DropDownList ID="ddlPersons" runat="server" AppendDataBoundItems="true" DataValueField="ID" DataTextField="Name">
<asp:ListItem> -- please select person -- </asp:ListItem>
</asp:DropDownList>
Then you can databind items from the database in the codebehind:
ddlPersons.DataSource = personsList;
ddlPersons.DataBind();
I regard this "empty item" as presentation / UI, so I like to put it in the aspx. It also keeps the codebehind simpler.
Do something like this: Here is a simple example
<asp:DropDownList ID="ddlFruits" runat="server">
<asp:ListItem Value="1" Text="Oranges"></asp:ListItem>
<asp:ListItem Value="2" Text="Apples"></asp:ListItem>
<asp:ListItem Value="3" Text="Grapes"></asp:ListItem>
<asp:ListItem Value="4" Text="Mangoes"></asp:ListItem>
</asp:DropDownList>
And in the code behind
ddlFruits.Items.Insert(0, new ListItem(string.Empty, "0"));
You can do it with this way:
dropdownlist1.Items.Insert(0, new ListItem("Select here...", string.Empty));
You can do it in SQL:
sql = #"Select Nome From DanielPessoas UNION ALL Select '' Order by Nome";
We can do this on the front end in C#
#Html.DropDownList("sample",new SelectList(DropDownList1, "DataTextField", "DataValueField "), "Select")