ASP.NET adding controls inside a loop - asp.net

Pardon me, this really is a noob question but please understand that I do not have much ASP.NET experience. All I need to do is:
1) Open up the following SQL query:
SELECT myid FROM mytable
2) For each record, generate this fragment of HTML:
<img src="http://someurl/__myid comes here as well__/small.png" />
Its easy for me to use the classical ASP <% do until recordset.eof ... loop %> style loops but I need it in ASP.NET style, probably perform the operation in Page_Load event and use intrinsic ASP.NET controls.

Use a repeater control. In the ItemTemplate, you can put whatever you would like to be generated for each record returned from your query.
http://articles.sitepoint.com/article/asp-net-repeater-control

add this in the aspx page source
<td id="urLink" runat="server">
</td>
add this in the Page_Load event
SqlConnection con = new SqlConnection();
con.connectionstring = "your connection database";
SqlDataReader reader;
SqlCommand command = new SqlCommand(con);
command.Commandtext = "SELECT myid FROM mytable";
command.CommandType = CommandType.Text;
reader = command.ExecuteReader();
while(reader.Read())
{
urLink.innerHTML += "<a href="#mynameanchor" onClick="myfunction( " + reader["myid"].tostring() + " );">
<img src="http://someurl/" + reader["myid"].tostring() + "/small.png" /></a>";
}

Looks like the onclick is a javascript event which means you can write out the HTML markup to a string and then append it all into a literal control. Remember to use a stringbuilder :)
here's a very basic example:
// get data from database and into a reader before
StringBuilder links = New StringBuilder();
while(reader.read())
{
links.appendFormat("<a HREF='id_{0}'>{0}</a>", reader["ID"]);
}
ltlLinks.Text = links.ToString();

Related

asp.net - how to display a field from data row that is in html format

I have a field of text in html format, in a row of data that I need to select and then display it in a aspx page as html.
The text contains html tags, symbols like & ; etc... and of course lots of double quotes. For example....
<li>products</li>Check out our full line of these products, bla bla bla....<br><font color="blue">View</font><td bgcolor="#000000" align="center"><b><font color="#FFFFFF">Diameter</font><li>30° Helix<li></td>
...etc
The method that I am trying to use to retrieve it with in the codebehind, gives me the error...
An exception of type 'System.Data.SqlClient.SqlException' occurred in
System.Data.dll but was not handled in user code
Additional information: Incorrect syntax near '='.
public void GetHtml()
{
string gethtml = Request.QueryString["product"];
string conString = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
string query = "SELECT htmlpull FROM ejn_html WHERE newseries LIKE = #gethtml";
SqlCommand cmd = new SqlCommand(query);
cmd.Parameters.Add("#gethtml", SqlDbType.VarChar, 70).Value = gethtml;
SqlConnection con = new SqlConnection(conString);
SqlDataAdapter sda = new SqlDataAdapter();
cmd.Connection = con;
sda.SelectCommand = cmd;
DataTable dt2 = new DataTable();
sda.Fill(dt2);
foreach (DataRow dtRow in dt2.Rows)
{
pulledhtml = dtRow[0].ToString();
}
}
The exception is triggered on the line that contains... sda.Fill(dt2);
In my aspx page I try to call the variable using...
<%= pulledhtml %>
This works fine when I try to retrieve any other string variables that contain normal alphanumeric characters. This is a very large database that I inherited and I am not allowed nor would I want to edit the html in those fields.
How can I retrieve this html code and display it without exception errors?
Your sql text is incorrect
SELECT htmlpull FROM ejn_html WHERE newseries LIKE = #gethtml
is invalid. you can't use LIKE and = together.
Change you sql to either
SELECT htmlpull FROM ejn_html WHERE newseries = #gethtml
for an exact match or
SELECT htmlpull FROM ejn_html WHERE newseries LIKE #gethtml
where you define the parameter value with wildcards
cmd.Parameters.Add("#gethtml", SqlDbType.VarChar, 70).Value = "%" + gethtml + "%";
for a match where the value of gethtml is contained in the column value.

InsertCommand inside of code behind

I came across the followng code in the code behind and wondering
if this may be a good practice in terms of inserting a record
programmatically:
protected void ButtonMain_Click(object sender, EventArgs e)
{
string sConn = ConfigurationManager.ConnectionStrings["SQL1"].ConnectionString;
SqlDataSource dbQ = new SqlDataSource();
dbQ.ConnectionString = sConn;
dbQ.InsertCommand = "INSERT INTO data1_DropDownLists (ParamID, ddlValue) VALUES ('" + ddlAllParams.SelectedValue + "','" +
txtddl.Text + "')";
dbQ.Insert();
DropDownGrid.DataBind();
dbQ = null;
}
What I have seen is before is something like:
string query = "INSERT INTO data1_DropDownLists vALUES ...";
cmd = new SqlCommand(query, conn);
conn.Open();
cmd.ExecuteNonQuery();
so was not sure of what the benefit may be to using the above method using InsertCommand
The SqlDataSource is a control in the System.Web namespace. It can be used as datasource for web-databound controls like Repeater or GridView.
It is a control which should be used declaratively on the aspx markup and not in codebehind. It's like an interface between the GUI and the DAL. Normally you should avoid this kind of hardlinking. Instead you should separate GUI(ASPX), BLL(codebehind or class libraries etc.) and DAL (ADO.NET or Entity framework etc.).
I would suggest to use the most direct way, using an ADO.NET SqlCommand:
// use using-statement to ensure that the connection gets closed even in case of an error
using (var con = new SqlConnection(connectionString))
{
using (var cmd = new SqlCommand("INSERT INTO dbo.Table(Column)VALUES(#Column)", con))
{
// use parameters to avoid SQL-Injection
cmd.Parameters.AddWithValue("#Column", value);
con.Open();
cmd.ExecuteNonQuery();
}
}
The SqlDataSource class has four command properties, one for each sql action: SelectCommand, InsertCommand, UpdateCommand, DeleteCommand.
Once an instance is created, each of the command property can be set.
The class also exposes a two arguments constructor SqlDataSource(String, String) where the second argument specifies the SELECT command text.

How to create ASP.Net Control In .aspx file dynamicly?

I have to create a series of controls(Hyperlink and Label) in .aspx file.The most important thing is that I have to control the ID of the generated control.
I write some code in my .aspx file like this:
<%for (int i =1; i <= 5; i++){%>
<asp:HyperLink ID="<%#GetContorlName("HyperLink",i,1)%>" CssClass="c083e01" runat="server">HyperLink</asp:HyperLink>
<%} %>
GetContorlName() is a function defined in codebehind file which return a string represent ID.
However,This doesn't work,It cannot compile.
Who can help me to fulfill this task?Please Remember I have to dynamically create controls in .aspx file,not in .cs file.
Any help will be appreciated!
Use ClientID.
http://msdn.microsoft.com/en-us/library/system.web.ui.control.clientid.aspx
Use databinding, and nest the controls in a repeater. Remember that Enumerable.Range() can be a valid datasource.
try this method for your Hyperlink
TextBox txt = new TextBox();
txt.ID = "strtxtbox";
txt.CssClass = "CSS1";
StringBuilder sb = new StringBuilder();
StringWriter writer = new StringWriter(sb);
HtmlTextWriter htmlWriter = new HtmlTextWriter(writer);
txt.RenderControl(htmlWriter);
//lbl is an aspx label
lbl.text += #"<td style='width: 5%;'>" + sb.ToString() + "</td>";

Pass NavigateUrl Id to next page Sql statement

I am coding "List all Product" page in asp.net. I did the connection from the DB to ViewList. Now I have to make the products clickable. What I have coded so far in the asp part is , as it follows:
<div class="image">
<asp:HyperLink ID="HyperLinkSaleDesign" runat="server" NavigateUrl='<%# Eval("ID" , "~/EN/ViewTemplate.aspx?id={0}") %>'>
<asp:Image ID="ImageSaleDesign" runat="server" Width="247" Height="150" ImageUrl='<%# Eval("thumb") %>' />
</asp:HyperLink>
</div>
The navigation URL works and I can see the selected "?id={0}".
However I cannot pass the data correctly , so the SQL query on the next page does not work.
I am not sure how to pass this value to the Select statement. Here is what I have done so far:
String IDquery = ("QueryStringParameter[ID]"); // doesn't work
try
{
string ConnectionString = WebConfigurationManager.ConnectionStrings["Twebconfig"].ConnectionString;
SqlConnection viewTemplate = new SqlConnection(ConnectionString);
SqlDataAdapter viewTemplateSet = new SqlDataAdapter("SELECT " +
" * FROM saleDesigns WHERE ID = #IDquery", viewTemplate); // doesn't seem to see the variable
Data Binding - etc. etc. etc
}
catch (Exception err)
{
mylabel.Text = "Invalid " + err.Message;
}
I am open to any suggestions.
Thank you.
I'm a bit confused by your code, but it looks like you just need to retrieve the id from QueryString and build a SQL query with it, right?
Is this what you're trying to do?:
int id = int.Parse(Request.QueryString["id"]);
You can put the query together using the ID from QueryString, you can do something like this:
//just an example - should be parameterized to avoid injection
string query = String.Format("SELECT ID, Col1, Col2 FROM Table1 WHERE ID={0}", Request.QueryString["ID"]);
This is the way it works for me:
int v = 0;
try
{
int v = int.Parse(Request.QueryString["id"]);
}
catch (Exception e)
{}
if (v > 0)
{
try
{
string ConnectionString = WebConfigurationManager.ConnectionStrings["connstring"].ConnectionString;
SqlConnection conn = new SqlConnection(ConnectionString);//explisionremoteEntities
string query = String.Format("SELECT * FROM table WHERE ID={0}", Request.QueryString["ID"]);
SqlDataAdapter viewTemplateSet = new SqlDataAdapter(query, conn);
}
catch
{
//code in here
}
}

ASP.NET store Image in SQL and retrieve for Asp:Image

I am looking to fileupload a picture jpeg,gif,etc into an SQL database on an updateprofilepicture page. Then on the profile page, I want to retrieve the image from an sql database and have it show up in an Asp:Image control. I have much code trying to do this and it doesn't work. The table contains a column of type Image.
As Joel mentioned you should use an HttpHandler or a page to display the image. Here is a sample code to output image (Image.ashx) :
// ProcessRequest method of Image.ashx
long imageId = Convert.ToInt64(Request.QueryString["ImageId"]);
using (var conn = new SqlConnection(connectionString))
using (var command = new SqlCommand(
"SELECT ImageFile FROM ImageTable WHERE ImageId = #ImageID", conn))
{
command.Parameters.Add("#ImageID", SqlDbType.Int).Value = imageId;
conn.Open();
Response.ContentType = "image/gif";
Response.BinaryWrite((byte[]) command.ExecuteScalar());
}
and then use image in your page as :
<asp:Image id="Image1" runat="server" ImageUrl="Image.ashx?ImageID=12"/>
The important thing to remember here is that you shouldn't try to transmit the image data with the profile page itself. Instead, you want your profile page to generate HTML markup for the browser that looks something like this:
<img src="~/MyImageHandler.ashx?UserID=1234" alt="User 1234 avatar" width="100px" height="150px" />
That is the ultimate result of your <asp:Image .../> control. Then the browser will send a completely separate Http request to retrieve the image. That's how pictures on web sites work. You then need to be able to handle that additional request. To do that, create an Http handler (*.ashx file) and use it to retrieve the appropriate image data from the database and send it to the browser.
If you're using SQL 2005 or greater you should not use the data type Image because it's now deprecated. Instead you want to use the new Varbinary(MAX) type if possible. Once you have it stored all you need to do is retrieve it via ADO.Net call and cast the cell value into type Byte[] and then call Response.BinaryWrite like in ScarletGarden's example above.
After a few hundred gigabytes of images, I believe you'll find yourself thinking that the operating systems' file system and static file http servers is better suited than the database, which is busy which a lot of other details, for storing images. It also allows you to use thousands of existing free tools to work with, move, host, etc the images.
Instead of storing images in the database, store the path and/or filename for the image. Images will fill up the database and make it slow.
protected void Page_Load(object sender, EventArgs e) {
GridView1.DataSourceID = "";
GridView1.DataSource = SqlDataSource1;
GridView1.DataBind();
}
protected void btnSubmit_Click(object sender, EventArgs e) {
string strImageName = txtImageName.Text.ToString();
if (FileUpload1.PostedFile != null && FileUpload1.PostedFile.FileName != "") {
byte[] imageSize = new byte[FileUpload1.PostedFile.ContentLength];
HttpPostedFile uploadedImage = FileUpload1.PostedFile;
uploadedImage.InputStream.Read(imageSize, 0, (int)FileUpload1.PostedFile.ContentLength);
// Create SQL Connection
SqlConnection con = new SqlConnection();
con.ConnectionString = "Data Source=RND3" + "\\" + "SQLEXPRESS;Initial Catalog=SSSolutionFiles;Integrated Security=True";
// Create SQL Command
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "INSERT INTO Imagess(ImageName,Image)" + " VALUES (#ImageName,#Image)";
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
SqlParameter ImageName = new SqlParameter("#ImageName", SqlDbType.VarChar, 50);
ImageName.Value = strImageName.ToString();
cmd.Parameters.Add(ImageName);
SqlParameter UploadedImage = new SqlParameter("#Image", SqlDbType.Image, imageSize.Length);
UploadedImage.Value = imageSize;
cmd.Parameters.Add(UploadedImage);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
Label1.Text = "File Uploaded";
GridView1.DataSourceID = "";
GridView1.DataSource = SqlDataSource1;
GridView1.DataBind();
con.Close();
}
}
Try these links it might help you..
you can also try by storing the image files on the server and store the paths on the Sql table..
by these links
http://pratikataspdotnet.blogspot.in/2014/11/retrieve-images-from-path-stored-in.html

Resources