So I am porting a legacy application over from coldfusion to asp.net/c#. My problem is, (and I have searched all over for it, but I may not be wording my problem properly to get good results), is that I want to take my results from a the first query I have, and perform a second query to fill in that column.
Here's how I did it in coldfusion:
<cfquery name="p" datasource="db">
select * from table
</cfquery>
<cfloop query="p">
<tr>
<td>
#p.title#
</td>
<td">
#p.category#
</td>
<td>
#CreateObject("component","/components.dao").getuser(p.userid).user_fullname()#
</td>
</tr>
</cfloop>
You'll notice I call a component and method that I send the userid from the query too. This method has another query that calls a seperate database, and returns information on that user, in this case the full name rather than just the userid. This is where I am having problems in asp.net/c# for that I have created the following code:
<asp:Repeater id="program_list" runat="server">
<ItemTemplate>
<tr>
<td>
<%# Eval("title") %>
</td>
<td>
<%# Eval("category") %>
</td>
<td>
<%# Eval("userid")%> (needs full name convert)
</td>
</tr>
</ItemTemplate>
</asp:Repeater>
and in the codebehind
protected void Page_Load(object sender, EventArgs e)
{
try
{
DbConnection connection = new SqlConnection();
connection.ConnectionString = "***";
connection.Open();
SqlCommand cmd = (SqlCommand)connection.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "SELECT * FROM table";
SqlDataReader reader = null;
reader = cmd.ExecuteReader();
program_list.DataSource = reader;
program_list.DataBind();
reader.Close();
connection.Close();
}
catch (Exception ex)
{
Response.Write(ex);
}
}
As you can see, it only does the first part, outputting the original query, but I am not sure how to interact with that query in order to call the database the second time for the users details. Any ideas would be greatly appreciated, thanks.
so you need to call an sql query each line of repeater. you should use ItemDataBoundEvent , in this event you can have processing rows user_id and can make another query.
for example
protected void Repeater1_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
DataRowView drw = (DataRowView)e.Item.DataItem
String sql = String.Format("Select * FROM UserInfo WHERE user_id={0}", drw["user_id"]);
Label lblUserName = (Label) e.Item.FindControl("lblUserName");
lblUserName.Text = //WWhatever you get from query...
}
You are looking for a ItemDataBound event. You can do a query in that event and populate other controls.
Related
I have used a datalist for displaying data from database. The code for it is:
<div id="ccont">
<asp:DataList ID="mydatalist" runat="server">
<ItemTemplate>
product:<asp:Label ID="lbl1" Text='<%#DataBinder.Eval(Container.DataItem,"product") %>' runat="server" />
<br/>
price:<asp:Label ID="lbl2" Text='<%#DataBinder.Eval(Container.DataItem,"price") %>' runat="server" />
</ItemTemplate>
</asp:DataList>
</div>
And its corresponding .cs file has the following code:
protected void Page_Load(object sender, EventArgs e)
{
sq.connection();
SqlCommand cmd = new SqlCommand("select * from sub_catTbl where sid = 1 " , sq.con);
SqlDataReader sd = cmd.ExecuteReader();
sd.Read();
mydatalist.DataSource = sd;
mydatalist.DataBind();
sq.con.Close();
}
This SQL query gives no output nor gives any error. When I replace SQL query with:
select * from sub_catTbl
It works. The output is:
So how do I make the SQL query with WHERE condition work?
Note: It's not working for where name='abc' as well.
EDIT: OK I have executed this query
select * from sub_catTbl where sid = 1
and it works fine. Here is the output:
I have had the same problem. Just remove the sd.Read() line and everything works great.
For further reference see https://unschoolingcode.wordpress.com/2012/08/16/my-computer-is-playing-video-on-its-own/ and http://msdn.microsoft.com/en-us/library/aa719635(v=vs.71).aspx
You didn't open the connection. Try to use sq.con.open();.
Here is the situation, I have a AJAX modal pop up, inside my panel is two(2) connected drop down list. One is for Continent, and the other one is for Countries. An example of it is when the user choose Asia, the drop down for countries should have data inside. here is my code for modal pop up and Panel
<asp:ModalPopupExtender ID="Modalpopupextender1" runat="server" TargetControlID="ShowPopUpButton"
PopupControlID="pnlpopup" CancelControlID="CancelButton" BackgroundCssClass="modalBackground">
</asp:ModalPopupExtender>
<asp:Panel ID="pnlpopup" runat="server" BackColor="White" Height="269px" Width="400px"
OnLoad="pnlpopup_Load">
<tr>
<td align="right">
Continent:
</td>
<td>
<asp:DropDownList ID="ContinentDownList" runat="server"
onselectedindexchanged="ContinentDropDownList_SelectedIndexChanged" AutoPostBack="true">
</asp:DropDownList>
</td>
</tr>
<tr>
<td align="right">
Country:
</td>
<td>
<asp:DropDownList ID="CountryDropDownList" runat="server">
</asp:DropDownList>
</td>
</tr>
</asp:Panel>
Now my Problem is, When my Modal Pop up loads, When I choose a Continent, the drop down for Countries doesnt load. When I Inserted AutoPostBack="true" to my ContinentDropDown, the Modal Pop Up refreshes, and exits. Ive spend a long time debugging and knowing how to fix this. Help!
here is my code-behind
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
LoadContinent();
LoadCountry();
}
}
public void LoadContinent()
{
using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString))
{
using (SqlCommand com = new SqlCommand("Reader.usp_LoadContinentDropDownList", con))
{
com.CommandType = CommandType.StoredProcedure;
con.Open();
try
{
SqlDataReader dr = com.ExecuteReader();
OwnerGroupDropDownList.DataSource = dr;
OwnerGroupDropDownList.DataTextField = "fld_Description";
OwnerGroupDropDownList.DataValueField = "fld_ContinentID";
ContinentDropDownList.DataBind();
}
catch (SqlException)
{
Response.Write("<script>alert('The database has encountered an error. Please try again')</script>"); }
catch (Exception)
{
Response.Write("<script>alert('The database has encountered an error. Please try again')</script>"); }
}
}
LoadContinentDropDownList.Items.Insert(0, new ListItem("<Select Person Group>", "0"));
}
public void LoadCountry()
{
using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString))
{
using (SqlCommand com = new SqlCommand("Reader.usp_LoadCountryDropDownList", con))
{
com.CommandType = CommandType.StoredProcedure;
com.Parameters.Add(new SqlParameter("#fld_ContinentId", SqlDbType.Int));
com.Parameters["#fld_ContinentId"].Value = ContinentDropDownList.SelectedValue;
con.Open();
try
{
SqlDataReader dr = com.ExecuteReader();
OwnerDropDownList.DataSource = dr;
OwnerDropDownList.DataTextField = "fld_Description";
OwnerDropDownList.DataValueField = "fld_CountryID";
CountryDownList.DataBind();
}
catch (SqlException)
{
Response.Write("<script>alert('The database has encountered an error. Please try again')</script>"); }
catch (Exception)
{
Response.Write("<script>alert('The database has encountered an error. Please try again')</script>"); }
}
}
CountryDropDownList.Items.Insert(0, new ListItem("<Select Person>", "0"));
}
protected void ContinentDropDownList_SelectedIndexChanged(object sender, EventArgs e)
{
LoadContinent();
LoadCountry();
}
Have you tried putting the pnlPopup panel inside of an ASP.NET UpdatePanel control? Now when your dropdown list does a postback, it will be a partial postback since they are both within an UpdatePanel and it should maintain the visibility on the popup panel.
Check out Introduction to the UpdatePanel Control for more information about creating and using the UpdatePanel.
When you put controls outside of an UpdatePanel, the AutoPostback="true" caused a full postback which "reset" the popup panel to hidden, since that is the default state for the modal popup extender's target control.
I have followed the tutorial at codeproject, and have stumbled into an issue.
I have a ListView, listing all the current members names of my site:
<asp:ListView ID="lstMembers" runat="server">
<LayoutTemplate>
<table>
<tr>
<th>Name</th>
</tr>
<tr id="itemPlaceholder" runat="server"></tr>
</table>
</LayoutTemplate>
<ItemTemplate>
<tr>
<td>
<%# Eval("MemberName") %>
</td>
</tr>
</ItemTemplate>
</asp:ListView>
And a DataPager underneath:
<asp:DataPager ID="DataPagerProducts" runat="server" PagedControlID="lstMembers"
PageSize="3" OnPreRender="DataPagerProducts_PreRender">
<Fields>
<asp:NumericPagerField />
</Fields>
</asp:DataPager>
I am using the following to bind to the List (As per the tutorial):
List<Members> member = new List<Members>();
protected void Page_Load(object sender, EventArgs e)
{
if(Page.IsPostBack) return;
DisplayMembers();
}
private void DisplayMembers()
{
const string strSql = "SELECT DISTINCT [id], [memberNickname] FROM vwGetMemberDetails ORDER BY [memberNickname]";
SqlCommand sqlComm = new SqlCommand(strSql, DataConn.Connect()) { CommandType = CommandType.Text };
SqlDataReader rdr = sqlComm.ExecuteReader();
while (rdr.Read())
{
member.Add(new Members
{
MemberId = rdr["id"],
MemberName = rdr["memberNickname"]
});
}
rdr.Close();
DataConn.Disconnect();
}
private class Members
{
public object MemberId { get; set; }
public object MemberName { get; set; }
}
protected void DataPagerProducts_PreRender(object sender, EventArgs e)
{
lstMembers.DataSource = member;
lstMembers.DataBind();
}
So there are currently 2 numbers on the Pager. But, every time I click 2, the List displays nothing, and the Pager disappears.
I am usually a frequent worker of the Repeater control, and am only using this method as an assumingly 'easier' way.
Can anyone tell me where I'm going wrong?
Your variable model is not updating in the DataPagerProducts_PreRender so it will always display the same dataset already loaded in the page load.
EDIT
removing if(Page.IsPostBack) return; or calling DisplayMembers() inside the DataPagerProducts_PreRender will work this for me
I have a repeater I want to add a title to in the HeaderTemplate from my database
This is my code so far
<asp:Repeater ID="topicView" runat="server">
<HeaderTemplate>
<tr>
<td>
<h1><%#DataBinder.Eval(Container.DataItem, "TopicName")%></h1>
</td>
</tr>
</HeaderTemplate>
<ItemTemplate>
<tr>
<td>
<%#DataBinder.Eval(Container.DataItem, "PostBody")%>
</td>
</tr>
</ItemTemplate>
<FooterTemplate>
<tr>
<td>
</td>
</tr>
</FooterTemplate>
</asp:Repeater>
But nothing is displaying in my header. I heard that you can't use databinder in the header, so could anyone recommend how to do this?
this is my CS code
string topic = Request.QueryString["topicid"].ToString();
// Define the select statement.
// All information is needed
string selectSQL = "SELECT * FROM PostView WHERE TopicID ='" + topic + "'";
// Define the ADO.NET Objects
SqlConnection con = new SqlConnection(connectionString);
SqlCommand cmd = new SqlCommand(selectSQL, con);
con.Open();
SqlDataReader postView = cmd.ExecuteReader();
topicView.DataSource = postView;
topicView.DataBind();
You don't need to bind to the data source, just bind to a simple property of the page. Use this in the HeaderTemplate:
<h1><%# TopicName %></h1>
Then add TopicName as a public property to the code-behind.
public string TopicName { get; set; }
Then set it when you run the query:
TopicName = Request.QueryString["topicid"].ToString();
Side Note
Not sure if you're aware, but you should be careful of SQL injection. Instead of injecting the query string directly into your SQL query, it's a good idea to use
string selectSQL = "SELECT * FROM PostView WHERE TopicID ='{0}';
Then add the topic to your SqlCommand as a parameter.
I am using ASP.NET, C#, Sql Server 2005 for my project and
I'm using the repeater control to form a table of users that are a member of a site and a button next to each user so that they can be added to your friends list. I have everything set up except I dont know how to get the specific info of each row after a button click. I mean,
How to send a friend request to a person whose username is displayed besides the button? or
How to access the the displayed username besides the button so that I can use it for my code?
My Script
<asp:Repeater ID="myrepeater" runat="server">
<HeaderTemplate>
<table style="font: 8pt verdana">
<tr style="background-color:#3C78C3">
<th>Search Result</th>
</tr>
</HeaderTemplate>
<ItemTemplate>
<tr>
<td>
<%#DataBinder.Eval(Container,"DataItem.allun")%>
<asp:Button ID="Button1" runat="server" Text="Button" />
</td>
</tr>
</ItemTemplate>
<FooterTemplate>
</table>
</FooterTemplate>
Code Behind
protected void btnSearch_Click(object sender, EventArgs e)
{
con.Open();
if (txtSearch.Text != "")
{
SqlDataAdapter mycommand = new SqlDataAdapter("select * from WebAdminTable where allun='" + txtSearch.Text + "'", con);
DataSet ds = new DataSet();
mycommand.Fill(ds);
myrepeater.DataSource = ds;
myrepeater.DataBind();
}
else
{
//msgbox for entering value
}
con.Close();
}
protected void btnAddToMyFList_Click(object sender, EventArgs e)
{
//?
}
You can bind the userName to a label control and then you can access the value of the label control on the click of button like...
protected void btnAddToMyFList_Click(object sender, EventArgs e)
{
Button btnAddToMyFList = (Button)sender;
Label label = (Label)btnAddToMyFList.Parent.FindControl("LabelId");
String labelText = label.Text; //userName of clicked row
}