Autocomplete Extender ajax on pressing enter key - c#

I have created Ajax autocomplete extender on my web page that retrieves the values from the database.
When I select one of the options from the autocomplete dropdown list I get the desired result.
The problem is:
When the user types entire word by himself (or if the word is pasted) and when he does not select one of the options from the dropdownlist and presses enter, result is blank.
How do I solve this problem?
My code for autocomplete extender is:
<asp:HiddenField ID="HiddenID" runat="server" />
<asp:ToolkitScriptManager ID="ToolkitScriptManager1" runat="server">
</asp:ToolkitScriptManager>
<asp:TextBox ID="SearchRetailer" runat="server" Style="background-image: url(Search-icon.png ); border: 1px groove black; background-position: right; background-repeat: no-repeat; float: right; width: 20%;" />
<asp:AutoCompleteExtender
ID="AutoCompleteExtender1"
TargetControlID="tgt1"
runat="server" MinimumPrefixLength="2" ServiceMethod="GetCompletionList" UseContextKey="True" OnClientItemSelected="GetCode" EnableCaching="true" />
The javascript function is:
<script type="text/javascript" language="javascript">
function GetCode(source, eventArgs) {
var hfield = $get('<%=this.HiddenID.ClientID%>');
hfield.value = eventArgs.get_value();
window.open("newPage.aspx?Paramter1=" + hfield.value + "", "_self", false);
}
</script>
And my webservice code is:
[System.Web.Services.WebMethodAttribute(), System.Web.Script.Services.ScriptMethodAttribute()]
public static string[] GetCompletionList(string prefixText, int count, string contextKey)
{
SqlConnection sqlconn = "my connection string"
string sql = "select abc from aaa where abc like '" + prefixText + "%'";
SqlDataAdapter cmd1 = new SqlDataAdapter(sql, sqlconn);
DataTable dt0r = new DataTable();
cmd1.Fill(dt0r);
int i = 0;
string[] rList = new string[dt0r.Rows.Count];
foreach (DataRow dr in dt0r.Rows)
{
rList.SetValue(dr["abc"].ToString(), i);
i++;
}
return rList;
}

I got it to work.
I added FirstRowSelected="true" in the properties of the autocomplete extender and the functionality is now working!!

Related

Hide html dropdownlist from the jquery dialog on specific rows of GridView

I'm new to Jquery, any help would be appreciated for below issue that m facing.
I have a GridView, on click of a row from Gridview(lnkView) a Jquery dialog(div:#dialog) opens which contains html dropdown(#projectcode) element.I want to hide the dropdown on click of certain rows.How to do that?
Code below: HTML
<script type="text/javascript">$("[id*=lnkView]").live("click", function () {
var datesent = $(this).next().text();
var subject = $(this).text();
var row = $(this).closest("tr");
$("#body").html($(".body", row).html());
$("#dialog").dialog({
width: 700,
title: subject,
buttons: [{
id: "ok", text: "Ok",
click: function () {
$(this).dialog('close');
}
}]
});
return false;
});
</script>
<asp:GridView ID="gvEmails" runat="server" DataKeyNames="MessageNumber" AutoGenerateColumns="False">
<Columns>
<asp:TemplateField HeaderText="Subject">
<ItemTemplate>
<asp:LinkButton ID="lnkView" runat="server" Text='<%# Eval("Subject") %>' />
<asp:LinkButton ID="lnkDateSent" runat="server" Text='<%# Eval("DateSent") %>' />
<span class="body" style="display: none">
<%# Eval("Body") %></span>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<div id="dialog" style="display: none" runat="server">
<span id="body"></span>
<select id="projectcode" runat="server">
<option value="">Please select...</option>
<option value="00111">Fedex - 001</option>
<option value="00112">UPS - 002</option>
</select>
<br />
</div>`
And below is the c# code
for (int i = count; i >= 1; i--)
{
Email email = new Email()
{
MessageNumber = i,
Subject = message.Headers.Subject,
DateSent = message.Headers.DateSent,
GUID = pop3Client.GetMessageUid(i),
};
SqlCommand comm = new SqlCommand("select GUID from Sample where GUID = '" + email.GUID + "' ", con);
SqlDataReader dr = comm.ExecuteReader();
if (dr.Read())
{
if (email.GUID == dr.GetString(0))
{
//The below condition what I want to achieve for a specific row which has email.GUID == dr.GetString()-- GUID
//projectcode.Attributes["disabled"] = "disabled";
// projectcode.Visible = false;
}
}
dr.Close();
con.Close();
}
If i understand you correctly you want an onclick function so when you click on a row in your gridview it will dropdown with information. When you click on it again you want it to hide.
so lets say this is one row in your gridview with aria-expanded set to true.
<tr class="toggle-display" aria-expanded="true">
<td>#information.Stuff</td>
</tr>
and here you have the message that will show in your dropdown.
<tr class="display-message">
<span>Information:</span> #information.Things
</tr>
The jquery would look like this.
$(document).ready(function () {
$(document).on('click', '.toggle-display', function (event) {
event.preventDefault();
if ($(this).next('.display-message').hasClass('expanded')) {
$(this).next('.display-message').removeClass('expanded');
$(this).attr('aria-expanded', "false");
} else {
$(this).next('.display-message').addClass('expanded', 1000);
$(this).attr('aria-expanded', "true");
}
});

How to Display a Gridview inside jquery dialog by clicking a link button inside another gridview

I have gridview showing columns BusRoute,BusNo and Action.Where action contains the linkbuttons to display another gridview.I want to display it in jquery dialog.My codes are.
ASPX Code:
First Gridview:
<asp:TemplateField>
<ItemTemplate>
<asp:LinkButton ID="lnkbtn" runat="server" OnClientClick="showDialog();">Shipment Status</asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</div>
</div>
Second Gridview:
<div class="gridview_stop" id="popup">
<asp:GridView ID="Stops" runat="server" AutoGenerateColumns="False" CellPadding="6" Width="190px">
<Columns>
<asp:BoundField HeaderText="Bus Stop" DataField="StopName" HeaderStyle-BackColor="#006B89">
<HeaderStyle BackColor="#006B89" Font-Size="18px" Font-Bold="false"></HeaderStyle>
<ItemStyle BackColor="#E0E0E0" HorizontalAlign="Center" />
</asp:BoundField>
</Columns>
</asp:GridView>
</div>
Code Behind File:
protected void search_Click(object sender, EventArgs e)
{
DataSet ds = new DataSet();
SqlDataAdapter adapter = new SqlDataAdapter();
con.Open();
SqlCommand cmd = new SqlCommand("spGetRoutes", con);
cmd.CommandType = System.Data.CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#BusStop1", Source.Text);
cmd.Parameters.AddWithValue("#BusStop2", Destination.Text);
adapter.SelectCommand = cmd;
adapter.Fill(ds);
adapter.Dispose();
cmd.Dispose();
con.Close();
if (ds.Tables[0].Rows.Count > 0)
{
Route.DataSource = ds.Tables[0];
Route.DataBind();
Stops.DataSource = null;
Stops.DataBind();
Lblmsg.Text = "";
}
else
Lblmsg.Text = "No Direct Bus Between These Stop";
Lblmsg.ForeColor = Color.WhiteSmoke;
Route.Dispose();
Route.DataBind();
Stops.Dispose();
Stops.DataBind();
}
protected void Route_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
e.Row.Attributes["onmouseover"] = "this.style.backgroundColor='aquamarine';";
e.Row.Attributes["onmouseout"] = "this.style.backgroundColor='white';";
e.Row.ToolTip = "Click last column for selecting this row.";
}
}
protected void OnSelectedIndexChanged(object sender, EventArgs e)
{
string Name = Route.SelectedRow.Cells[0].Text;
SqlDataAdapter adapter1 = new SqlDataAdapter();
DataSet ds1 = new DataSet();
string connetionString = "Data Source=.;Initial Catalog=BusService;uid=sa;Password=Murli#925";
SqlConnection connection = new SqlConnection(connetionString);
connection.Open();
SqlCommand cmd = new SqlCommand("spGetStops", connection);
cmd.CommandType = System.Data.CommandType.StoredProcedure;
int BusNo= Convert.ToInt32(Name);
cmd.Parameters.AddWithValue("#BusNo",BusNo);
adapter1.SelectCommand = cmd;
adapter1.Fill(ds1);
adapter1.Dispose();
cmd.Dispose();
connection.Close();
Stops.DataSource = ds1.Tables[0];
Stops.DataBind();
}
Jquery Function:
<script type="text/javascript">
$("#lnkbtn").live("click",
function showDialog() {
$("#popup").dialog({
show: { effect: "fold", duration: 4000 },
hide: { effect: "fold", duration: 4000 },
});
return false;
});
$(document).click(function (event) {
if (!$(event.target).closest('#popup').length) {
if ($('#popup').is(":visible")) {
$('#popup').dialog('close');
}
}
})
</script>
Thanks & Regards.
Take a look at your rendered html when you run the page. Unless you set ClientIDMode to Static I doubt that your button ID's are $("#lnkbtn") but more like $("#gvWhatever_lnkbtn_0")
Set OnClientClick="showDialog();" or $("#lnkbtn").live("click", function showDialog(){...}) no need to do both.
Using a Server Control button to activate a popup usually doesn't work. Especially if GridView Row Selection is enabled. I can't tell if your first GridView has that feature enabled as I only see a portion of the listing. But what tends to happen is you trigger a postback while trying to display the popup so you never see the popup.
Also your second popup contains a gridview, which requires a databind. so you need to make sure the gridview is populated with the data before activating the popup
Two methods for showing a popup using jquery from within a Gridview:
A portion of a GridView markup with 2 TemplateField's
<asp:TemplateField HeaderText="Info">
<ItemTemplate>
<div>
<div class="rs-icon rs-icon-info tooltip-marker" role="button">
</div>
<div id="ContactInfo" style="display:none;">
<table id="tblContactDetail" class="ContactDetail Note">
<tr>
<td style="width: 80px">Name</td>
<td style="width: 100%">
<asp:Literal ID="Literal1" runat="server"
Text='<%# Eval("expert_name") %>' />
</td>
</tr>
.
.
.
</table>
</div>
</div>
<ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="CV">
<ItemTemplate>
<div id="divButtonViewCV" runat="server"
class="rs-icon rs-icon-cv" role="button"
onclick='<%# Eval("expert_cv_id", "ViewPDF({0})") %>' >
</div>
</ItemTemplate>
</asp:TemplateField>
In the above markup I'm setting up for two styles of "popup". The first Template uses jQueryUI ToolTip widget which is activated on mouseover/out. This is nice because it doesn't require a click which means no worries about a postback mucking up the works. The interesting thing here is that I'm using a div as button.
How it works: The div with the .tooptip-marker class is set up to activate a jqueryui tooltip which will display the contents of <div id="ContentInfo"> by grabbing the inner html of the sibling div of the activating button. Note that this div is styled as display:none; so that the content is available for the tooltip but hidden so the main GridView displays as normal.
For brevity, I included only a portion of the content of <div id="ContentInfo">. But It can contain anything really. In my code it's a simple <table> containing contact information fields (using bound <asp:Literal> controls) that are part of the primary GridView data source.
But this could just have easily been an embedded GridView with it's own data source that is bound in the OnRowDatabound event of the primary GridView.
The following jquery sets up the widget. See jQueryUI ToolTip widget for more complete documentation
$( function() {
$( document ).tooltip( {
items: ".tooltip-marker",
content: function() {
return $( this ).next().html();
},
position: {
my: "left top",
at: "right+5 top-5"
}
} )
} );
The second Template field is used to activate a popup. This is where you have to be careful about postbacks. Again I use a <div> styled as an icon and treated as a simple button because I've added onclick.
Clicking this button displays a popup so you can view a persons CV in PDF format. The PDF is stored in our database as a varbinary. Here I use another jquery addon, (colorbox), to display the PDF as a popup over the page.
In the ViewPDF() function below note that we prevent the "bubbling up" of the click event to the GridView by setting cancelBubble = true (for older IE) or a call to stopPropagation() (all other browsers).
In this code, colorbox sets up an iframe and passes the href parameter to its src attribute. I'm making a call to an .ashx page which is an asp Generic Handler which allows us to serve up other type of content without standard web page overhead. This could just as easily been configured to accept a standalone .aspx page where you could maybe place your secondary grid.
// This plain object is used by the call to colorbox(), please
// refer to colorbox documentation for details.
var colorboxDataExpertCV = {
height: "85%",
width: 900,
opacity: .30,
fixed: true,
iframe: true,
returnFocus: false,
href: ''
}
// ========================================================
// In the Template above, the onclick code:
// onclick='<%# Eval("expert_cv_id", "ViewPDF({0})") %>'
//
// Renders to:
// onclick="ViewPDF(12345)"
//
// PdfHandlerExpertsCV.ashx is an GenericHandler that retrieves
// the CV from our database and writes the byte array to the
// colorbox iframe as an "application/pdf" content type which
// triggers native browser pdf management either by internal
// viewer or installed PDF plugin
// ========================================================
function ViewPDF( p ) {
if ( event.stopPropagation )
event.stopPropagation();
else
event.cancelBubble = true;
if ( p && p > 0 ) {
colorboxDataExpertCV.href = "/PdfHandlerExpertsCV.ashx?cvid=" + p;
$.colorbox( colorboxDataExpertCV );
}
return false;
}
Addendum
Let me make it more clear, I need to bind the data in 2nd Gridview and
display this Gridview2 in Jquery dialog .This data will be binded and
displayed in dialog from on the click event of linkbutton inside
Gridview1
As I said above, you cannot bind a GridView (server side event) and then popup a jquery ui dialog (client side event) without introducing much more complexity. You have to make sure all the data you need for the popup is available by the time you're ready to hit the button that opens the dialog.
The simplest way to accomplish this is to embed GridView2 within GridView1 and take care of the binding all at once. It's not pretty or efficient and, depending on the number of items shown in each, can slow down the page. But if you have only a few lines for each it should be acceptable.
Embed GridView2 and DataSource2 in the <ItemTemplate> of a <TemplateField> of GridView1.
Bind GridView2 in the RowDataBound event of Gridview1 using an appropriate row field or datakey field from GridView1 and then calling GridView2.DataBind().
Add a element to the same TemplateField
Refer to the jquery dialog modal form example which shows how to trigger a dialog from a button click. In your case substitute the second GridView for the Form in the example.
IMPORTANT be mindful that gridview row item id's get "mangled" so you should not use id's in the jquery calls but use jquery selectors that are based on element name plus class markers, ie: $("button.marker") for a button defined like this: <button class="marker">.
Addendum: 2015-Jun-24
CSS (<head> tag)
<link rel="stylesheet" type="text/css" href="css/smoothness/jquery-ui.css" />
<script type="text/javascript" src="Scripts/jquery-2.1.4.min.js"> </script>
<script type="text/javascript" src="Scripts/jquery-ui-1.11.4.min.js"> </script>
<style>
.btn_styling {
text-align: center;
width: 32px;
margin: 2px;
cursor: pointer;
border: 1px solid gray;
border-radius: 3px;
/* add a background image to the div
to make the div look like a button */
/* background-image: url('...') */
}
.ui-dialog-titlebar-close {
display: none;
}
</style>
HTML (.aspx)
<form id="form1" runat="server">
<div style="width: 400px;">
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
DataKeyNames="user_id"
DataSourceID="SqlDataSource1">
<Columns>
<asp:BoundField DataField="user_name" HeaderText="User Name" SortExpression="user_name" />
<asp:TemplateField HeaderText="Info">
<ItemTemplate>
<div id="divButton" runat="server" class="btn_styling dialog-marker" title="This could also have been a <button> element or maybe an <img> element...anything really">X</div>
<div style="display: none;">
<asp:GridView ID="GridView2" runat="server"
AutoGenerateColumns="False"
DataSourceID="SqlDataSource2">
<Columns>
<asp:BoundField DataField="email" HeaderText="Email" SortExpression="email" />
<asp:BoundField DataField="add_edit_date" HeaderText="Date Added" SortExpression="add_edit_date" DataFormatString='{0:dd-MMMM, yyyy}'/>
<asp:BoundField DataField="add_edit_by" HeaderText="Added By" SortExpression="add_edit_by" />
</Columns>
</asp:GridView>
<asp:SqlDataSource ID="SqlDataSource2" runat="server"
ConnectionString="<%$ ConnectionStrings:YourConnectionString %>"
SelectCommand="SELECT email, add_edit_date, add_edit_by FROM tbl_users WHERE (user_id = #user_id)">
<SelectParameters>
<asp:Parameter Name="user_id" />
</SelectParameters>
</asp:SqlDataSource>
</div>
</ItemTemplate>
</asp:TemplateField>
</Columns>
<RowStyle BorderColor="Blue" BorderStyle="Solid" BorderWidth="1px" />
</asp:GridView>
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:YourConnectionString %>"
SelectCommand="SELECT top 10 user_id, user_name from tbl_users">
</asp:SqlDataSource>
</div>
<div id="dialogContainer">
</div>
</form>
Code Behind (VB):
Private Sub GridView1_RowDataBound(sender As Object, e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles GridView1.RowDataBound
If e.Row.RowType = DataControlRowType.DataRow Then
Dim gv2 As GridView = DirectCast(e.Row.FindControl("GridView2"), GridView)
Dim sds As SqlDataSource = DirectCast(e.Row.FindControl("SqlDataSource2"), SqlDataSource)
sds.SelectParameters("user_id").DefaultValue = GridView1.DataKeys(e.Row.RowIndex).Value
gv2.DataBind()
End If
End Sub
jQuery to implement Dialog:
<script type="text/javascript">
var dialogOptions = {
autoOpen: false,
appendTo: "#dialogContainer",
modal: true,
height: "auto",
width: "auto",
title: "Dialog Title",
closeOnEscape: true,
buttons: {
Cancel: function() {
$( this ).dialog( "close" );
}
}
};
$( function() {
$( ".dialog-marker" ).on( "click", function() {
var d = $( this ).next( "div" ).first().dialog( dialogOptions );
d.dialog( "open" );
} );
} );
</script>

How to type data top to bottom (Top one should be new post and last one should be oldest one) asp.net c#

I am creating a social network website as facebook, but that website has some errors with posing status , i used following code to post status. I called this method on page_Load event and post button
private DataSet GetData()
{
string CS=ConfigurationManager.ConnectionStrings["RegistrationConnectionString"].ConnectionString;
using (SqlConnection con = new SqlConnection(CS))
{
SqlDataAdapter da = new SqlDataAdapter("Select * from PhotoStatusProfile WHERE Email = '" + Session["Email"].ToString() +"'",con);
DataSet ds = new DataSet();
da.Fill(ds);
return ds;
}
}
This is html code
<asp:Repeater runat="server" ID="Repeater1">
<ItemTemplate>
<div class="yourDivClass" style="border-top: thin none #BBCEB3; border-bottom: thin none #BBCEB3; padding: 10px; height: 121px; width: 548px; margin-top: 10px; right: 10px; left: 10px; border-left-width: thin; margin-left: 15px; background-color: #e9eaee; border-left-color: #BBCEB3; border-right-color: #BBCEB3;">
<br />
<div style="width: 58px; height: 62px">
<asp:Image ID="Image1" runat="server" Height="59px" ImageAlign="Top" ImageUrl="~/Profile/Image/supun_Profilemini.jpg" Width="55px" />
</div>
<div style="width: 307px; height: 21px; margin-left: 65px; margin-top: -60px">
<asp:Label ID="Label2" runat="server" Font-Bold="True" Font-Names="Arial" ForeColor="#000066" ><%#Eval("name") %> </asp:Label>
</div>
<div style="height: 22px; width: 461px; margin-left: 78px; margin-top: 11px"> <asp:Label ID="Label8" runat="server"><%#Eval("Status") %></asp:Label>
<br><br>
</div>
</div>
</ItemTemplate>
post button cs code
protected void Post_Click(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["RegistrationConnectionString"].ConnectionString);
conn.Open();
try
{
string inserQuery = "insert into PhotoStatusProfile(Name,Status,Email) values (#Name,#Status,#e)";
SqlCommand commm = new SqlCommand(inserQuery, conn);
commm.Parameters.AddWithValue("#Name", ProfileName.Text);
commm.Parameters.AddWithValue("#Status",TextBox1.Text);
commm.Parameters.AddWithValue("#e", Label1.Text);
commm.ExecuteNonQuery();
Label1.Text = Session["Email"].ToString();
}
catch (Exception ex)
{
Response.Write("Error -->" + ex.ToString());
conn.Close();
}
// LoadData();
Repeater1.DataSource = GetData();
Repeater1.DataBind();
TextBox1.Text = "";
}
But After i'm posting some status I faced some errors.
1,On this website, my new post displayed on bottom and oldest one on top but i want new post to top and others Gradually top to bottom ,(descending order by considering time)
when i posted big status, it will display Like this.
I want to fix this also.
Thanks
You should think about storing some kind of date for each post. Then you can get a sorted list from the database. Something like this:
SqlDataAdapter da = new SqlDataAdapter("Select * from PhotoStatusProfile WHERE Email = '" + Session["Email"].ToString() +" order by CreatedAt desc'",con);
This would also allow you to show a "posted"-Date, show posts by day/week/month etc.
Reversing Repeater order
To make a long word wrap you can apply css:
word-wrap: break-word;

How to pass div to the while loop, asp.net c#

I am creating a social network website as facebook, but that website has an error with posing status , i used following code to post status.This code is on page load,
Label1.Text = Session["Email"].ToString();
if (!IsPostBack)
{
//load data
string db = "";
db = ConfigurationManager.ConnectionStrings["RegistrationConnectionString"].ConnectionString;
SqlConnection con = new SqlConnection(db);
con.Open();
try
{
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "SELECT Name,Status FROM [PhotoStatusProfile] WHERE Email = #Email";
cmd.Parameters.AddWithValue("#Email", Session["Email"].ToString());
cmd.Connection = con;
SqlDataReader dr;
dr = cmd.ExecuteReader();
string status = "";
string name = "";
while (dr.Read())
{
System.Web.UI.HtmlControls.HtmlGenericControl div = new System.Web.UI.HtmlControls.HtmlGenericControl("div");
Label nameLabel = new Label();
status += dr["Status"].ToString();
name += dr["name"].ToString();
nameLabel.Text = name;
Label statusLabel = new Label();
statusLabel.Text = status;
div.Controls.Add(nameLabel);
div.Controls.Add(statusLabel);
container.Controls.Add(div);
}
con.Close();
}
I am passing value to a div which name is container.
When i write a status saying hi,and click the post button but nothing happen, then i refresh the page, and it has posted like this
2nd time i do the same thing saying hello, this is the result of it.
This is container. it's a name of a div tag
<div id="container" runat="server"> </div>
This is post button event
string inserQuery = "insert into PhotoStatusProfile(Name,Status,Email) values (#Name,#Status,#e)";
SqlCommand commm = new SqlCommand(inserQuery, conn);
commm.Parameters.AddWithValue("#Name", ProfileName.Text);
commm.Parameters.AddWithValue("#Status",TextBox1.Text);
commm.Parameters.AddWithValue("#e", Label1.Text);
commm.ExecuteNonQuery();
I want to post the status for down to down,
Could anybody tell me , what should i do to prevent this errors. Thaks
I'd suggest you to do the following re-factoring to your code.
Extract the code between following if block in your Page_Load and create a method called LoadData().
if(!IsPostBack)
{
LoadData();
}
Then in your Post button's click event call this LoadData() method again just after saving your new post to the database.
Instead of Labels to display values use DIVs (I mean nameLabel and statusLabel)
Also add following style to these DIVs
style="float:left;"
This is how you'd add it in code behind
div.Style.Add("float", "left");
UPDATE 1
Here's how you'd add DIVs instead of Labels.
HtmlGenericControl divContainer = new HtmlGenericControl("div");
HtmlGenericControl nameDiv = new HtmlGenericControl("div");
// Not sure why you concatenate Name and Status here. I'll just use one value per each row
// status += dr["Status"].ToString();
// name += dr["name"].ToString();
nameDiv.InnerText = dr["name"].ToString();
nameDiv.Style.Add("float", "left");
divContainer.Controls.Add(nameDiv);
HtmlGenericControl statusDiv = new HtmlGenericControl("div");
statusDiv.InnerText = dr["Status"].ToString();
statusDiv.Style.Add("float", "left");
divContainer.Controls.Add(statusDiv);
container.Controls.Add(div);
UPDATE 2
Since you've adopted #mybirthname solution (using a Repeater) I'll just give you the design you want based on DIVs.
<asp:Repeater runat="server" ID="Repeater1">
<ItemTemplate>
<%--This is your template--%>
<div style="margin-top: 5px;">
<div style="padding: 2px; border: 1px solid black; background-color:Silver; display:table; width:600px;">
<div style="float:left;">
<div style="padding: 4px">
<asp:Image ID="Image1" runat="server" ImageUrl="~/Images/my-avatar.PNG" /> <%--Give the correct path to your image--%>
</div>
</div>
<div>
<div style="font-size: 16px; font-family: Arial, Helvetica, sans-serif; font-weight: bold; padding-top: 4px;">
<%#Eval("name") %>
<div style="float:right; font-size: 10px;">9:00 am</div> <%--If you need to have a time stamp for each entry make use of this div--%>
</div>
<div style="width:500px;"><%#Eval("Status") %></div>
</div>
</div>
</div>
<%--End template--%>
</ItemTemplate>
</asp:Repeater>
From what I see you are adding the div to container and nameLabel, StatusLabel to div on every iteration of the DataReader. Probably this is not your intention, You want to add them once, because you are storing in status all values of Status row.
while (dr.Read())
{
status += dr["Status"].ToString();
name += dr["name"].ToString();
}
System.Web.UI.HtmlControls.HtmlGenericControl div = new
System.Web.UI.HtmlControls.HtmlGenericControl("div");
container.Controls.Add(div);
Label nameLabel = new Label();
nameLabel.Text = name;
div.Controls.Add(nameLabel);
Label statusLabel = new Label();
statusLabel.Text = status;
div.Controls.Add(statusLabel);
Also it will be good idea to put some ID to the labels. I advice you to put labels and div always and just make them visible false if there are no values in them.
Also if you add dynamically controls do it always in CreateChildControls() method.
EDIT: For what you want(written in my comments) you need a repeater. Check this tutorial in MSDN
<div id="container">
<asp:Repeater runat="server" ID="Repeater1">
<ItemTemplate>
<div class="yourDivClass">
<asp:Label runat="server"> <%#Eval("Status") %> </asp:Label>
<asp:Label runat="server"> <%#Eval("name") %> </asp:Label>
</div>
</ItemTemplate>
</asp:Repeater>
</div>
And in the code behind in Page_Load method:
if(!PostBack)
{
//in data set you will have dataTable with all rows and this rows should contain Name and Status columns
Repeater1.DataSource = dataSet;
Repeater1.DataBind();
}

How to bind image and video in same datalist?

My question is I have two coloumns video_url and image_src
I want bind this in single datalist at same time aspx code
<asp:DataList ID="DataList2" runat="server">
<ItemTemplate>
<li>
<script type="text/javascript">
function dd() {
var s = '<%#Eval("Video_url")%>';
if (s == "") {
"<a href='Client_website/raymond_shop.aspx'><img style='width: 245px; height: 220px;' src=Ads_image/" + <%#Eval("Image")%> +"/></a>";
}
else {
" <iframe frameborder='0' allowfullscreen='' src='" +<%#("Video_url")%> +"' style='width: 245px; height: 180px;' id='Iframe2'></iframe>";
}
}
</script>
<%-- <iframe frameborder="0" allowfullscreen="" src="//www.youtube.com/embed/icr2X5aKRMU" style="width: 245px; height: 180px;" id="Iframe2"></iframe>--%>
</li>
</ItemTemplate>
</asp:DataList>
C# code
public void fi()
{
ds = cat.fill("tbl_Main_ads where status=1");
DataList2.DataSource = ds;
DataList2.DataBind();
}

Categories

Resources