I'm writing the nodes of an XML to the database columns but I want to delete all (*) from the database before XML is written to the table again.
Right now if a user with userid '100' is inserted into the db, the code doesn't check for dupes and I'll have more than 1 userid '100's in the db. I need to check if the column id (for example) matches the id node of the xml. if there is a match, update the v and a nodes, if no match in the table then insert the id, v, and a nodes into the table
I created a function, private void deleteFromDb(string table) but I cant seem to call it (if I did it correctly in the first place) before the XML data is inserted into the table. But this wipes out all the data but the last person who accesses the page
<%# Page Language="C#"%>
<%# Import namespace="System.Net"%>
<%# Import namespace="System.Data"%>
<%# Import namespace="System.Data.SqlClient"%>
<%# Import namespace="System.IO"%>
<%# Import namespace="System.Xml"%>
<%# Import Namespace="System" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server" language="C#">
public class XML
{
internal string connString = ConfigurationManager.ConnectionStrings["LocalSqlServer"].ToString();
private void add2Db(string table, string sqlRows, string sqlValues)
{
string sql = String.Format("INSERT INTO {0} ({1}) VALUES ({2})", table, sqlRows, sqlValues);
using (SqlConnection dbConn = new SqlConnection(connString))
{
using (SqlCommand cmd = new SqlCommand(sql, dbConn))
{
cmd.Connection.Open();
cmd.ExecuteNonQuery();
}
}
}
private void deleteFromDb(string table)
{
string sql = String.Format("DELETE *", table);
using (SqlConnection dbConn = new SqlConnection(connString))
{
using (SqlCommand cmd = new SqlCommand(sql, dbConn))
{
cmd.Connection.Open();
cmd.ExecuteNonQuery();
}
}
}
public void parseXML(XmlDocument doc)
{
string tsLogpro = "";
string sqlRows = "";
string sqlValues = "";
//SELECT NODE: logPro
foreach (XmlNode logPro in doc.SelectNodes("broadcasting"))
{
tsLogpro = logPro.SelectSingleNode("#ts").InnerText;
//SELECT CHILD NODE: logPro
foreach (XmlNode child in logPro.ChildNodes)
{
//GET ROWS
foreach (XmlNode rows in child.Attributes)
{
sqlRows += rows.Name + ", ";
}
//GET VALUES
foreach (XmlNode values in child.Attributes)
{
sqlValues += "'" + values.InnerText + "', ";
}
sqlRows = sqlRows.Substring(0, sqlRows.Length - 2);
sqlValues = sqlValues.Substring(0, sqlValues.Length - 2);
//Response.Write("\n\n");
//Response.Write(sqlRows);
//Response.Write("\n" + sqlValues);
add2Db("flashcoms_chat7_broadcast", sqlRows, sqlValues);
sqlValues = "";
sqlRows = "";
}
}
}
}
protected void Page_Load(object sender, EventArgs e)
{
Response.Clear();
Response.ExpiresAbsolute = DateTime.Now;
Response.AddHeader("Content-type", "text/plain");
HttpRequest request = HttpContext.Current.Request;
System.IO.Stream body = request.InputStream;
System.Text.Encoding encoding = request.ContentEncoding;
System.IO.StreamReader reader = new System.IO.StreamReader(body, encoding);
XmlDocument doc = new XmlDocument();
string s = reader.ReadToEnd();
if (Request.Params["action"] != string.Empty && Request.Params["action"] == "test")
{
doc.InnerXml = "" +
"<broadcasting ts=\"12345\">" +
"<u id=\"1\" v=\"true\" a=\"true\" />" +
"<u id=\"2\" v=\"true\" a=\"true\" />" +
"<u id=\"3\" v=\"true\" a=\"false\" />" +
"<u id=\"4\" v=\"true\" a=\"true\" />" +
"<u id=\"5\" v=\"true\" a=\"true\" />" +
"</broadcasting>";
}
else if (!string.IsNullOrEmpty(s))
{
doc.InnerXml = s;
}
// Starting at line 111 in your original post
XML oXML = new XML();
oXML.deleteFromDb("f_chat7_broadcast")
oXML.parseXML(doc);
Response.Write("Done");
Response.End();
}
/*
*
*
SET ANSI_NULLS ON
GO
USE [DB]
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[f_chat7_broadcast](
[id] [nchar](100) NULL,
[v] [nchar](10) NULL,
[a] [nchar](10) NULL
) ON [PRIMARY]
GO
*
*/
</script>
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title>blah blah</title>
</head>
<body>
<form id="Form2" method="post" runat="server"><% Page_Load(null, null); %></form>
</body>
</html>
this
string sql = String.Format("DELETE *", table);
should be
string sql = String.Format("DELETE FROM {0}", table);
another point:
as far as I can see you don't have setup any exception handling (try / catch...) which is a bad practice...
Related
I am very new to C#, I am working in a program than downloads a file data with data from SQL Server database, the issue the query it always brings the same old now nonexistent data in the file.
This is the services BORA.asmx.cs:
using System;
using System.Collections.Generic;
using System.Collections;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Data;
using System.Text;
using LST.Enums;
using LST.Extensions;
using LST.Global;
using LST.Methods;
using Newtonsoft.Json;
using System.Diagnostics.Tracing;
namespace BORA
{
[WebMethod(EnableSession = true)]
public byte[] generateReport()
{
var vUser = Session["rep-users"];
var vCat = Session["rep-categories"];
var vStatus = Session["rep-status"];
var vAreas = Session["rep-areas"];
string strWhere = "";
if (vUser.fwEmpty() != "")
strWhere += (strWhere == "" ? "" : " AND ") + "P.Owner IN (" + vUser.ToString().fwSqlFilterIn() + ")";
if (vCat.fwEmpty() != "")
strWhere += (strWhere == "" ? "" : " AND ") + "Category IN (" + vCat.ToString().fwSqlFilterIn() + ")";
if (vStatus.fwEmpty() != "")
strWhere += (strWhere == "" ? "" : " AND ") + "P.Status IN (" + vStatus.ToString().fwSqlFilterIn() + ")";
if (vAreas.fwEmpty() != "")
strWhere += (strWhere == "" ? "" : " AND ") + "Area IN (" + vAreas.ToString().fwSqlFilterIn() + ")";
if (strWhere != "") strWhere = " WHERE " + strWhere;
System.Diagnostics.Debug.WriteLine("strWhere = " + strWhere);
LST.Methods.clsMethodsWeb fw = new clsMethodsWeb();
string strPathOrigin = fw.appGetPath + "excel\\template.xlsx";
string strPathDest = fw.appGetPath + "excel\\{0}.xlsx".fwFormat(Session["User"].ToString().ToLower().Replace(".", ""));
string strTable = "";
string strPID = "";
strPID = "WHERE PID IN (" +
#"SELECT P.PID
FROM tbl_Project_Tasks P
LEFT OUTER JOIN tbl_Project_Details D
ON P.PID = D.PID {0}"
.fwFormat(strWhere)
.fwSqlFillDataTable()
.fwDistinctValues("PID")
.fwSqlFilterIn() + ")";
if (strPID.fwEmpty() == "") return null;
fw.fileCopy(strPathOrigin, strPathDest);
DataTable dt = #"SELECT *
FROM tbl_Project_Tasks {0}"
.fwFormat(strPID)
.fwSqlFillDataTable();
dt.TableName = "Tasks";
strTable = "tblTasks";
LST.EPP.stcEpp.exportToByteArray(new DataTable[] { dt },
strPathDest, strTable: strTable, blnSave: true);
// ** Tasks
dt = #"SELECT *
FROM tbl_Project_Details D
LEFT OUTER JOIN tbl_Project_SavingType S
ON D.PID = S.PID
{0}"
.fwFormat(strPID.Replace(" PID ", " D.PID "))
.fwSqlFillDataTable();
dt.TableName = "Projects";
strTable = "tblProjects";
LST.EPP.stcEpp.exportToByteArray(new DataTable[] { dt }, strPathDest, strTable: strTable, blnSave: true);
// ** Projects
dt = #"SELECT REPLACE(REPLACE(SavingType, '(', ''), ')', '') Project, SUM(Saving) Projected, SUM(SavingFinal) Confirmed
FROM tbl_Project_SavingType
{0}
GROUP BY SavingType"
.fwFormat(strPID)
.fwSqlFillDataTable();
dt.TableName = "Project consolidate";
strTable = "tblProjectConsolidate";
LST.EPP.stcEpp.exportToByteArray(new DataTable[] { dt }, strPathDest, strTable: strTable, blnSave: true);
// ** Project consolidate
// ** tblProjectConsolidate
dt = #"SELECT Status, Count(Status) Count
FROM tbl_Project_Tasks
{0}
AND ISNULL(Status, '') <> ''
GROUP BY Status"
.fwFormat(strPID)
.fwSqlFillDataTable();
dt.TableName = "Task status";
strTable = "tblTaskStatus";
LST.EPP.stcEpp.exportToByteArray(new DataTable[] { dt },
strPathDest, strTable: strTable, blnSave: true);
// ** Task status
// ** tblTaskStatus
dt = #"Select Status, COUNT(Status) Count
FROM tbl_Project_Details
{0}
GROUP BY Status"
.fwFormat(strPID)
.fwSqlFillDataTable();
dt.TableName = "Project status";
strTable = "tblProjectStatus";
LST.EPP.stcEpp.exportToByteArray(new DataTable[] { dt },
strPathDest, strTable: strTable, blnSave: true);
// ** Project status
// ** tblProjectStatus
dt = #"Select Category, COUNT(Category) Count
FROM tbl_Project_Details
{0}
GROUP BY Category
ORDER BY Count"
.fwFormat(strPID)
.fwSqlFillDataTable();
dt.TableName = "Project categories";
strTable = "tblProjectCategories";
LST.EPP.stcEpp.exportToByteArray(new DataTable[] { dt },
strPathDest, strTable: strTable, blnSave: true);
// ** Poject categories
// ** tblProjectCategories
dt = #"Select Area, Count(Area) Count
FROM tbl_Project_Details
{0}
GROUP BY Area
ORDER BY Count"
.fwFormat(strPID)
.fwSqlFillDataTable();
dt.TableName = "Project areas";
strTable = "tblProjectAreas";
return LST.EPP.stcEpp.exportToByteArray(new DataTable[] { dt },
strPathDest, strTable: strTable);
// ** Project areas
// ** tblProjectAreas
}
[WebMethod(EnableSession = true)]
public string getReportOptions()
{
string dtArea = ("SELECT DISTINCT AREA FROM tbl_Maint_Area").fwSqlFillDataTable().fwDistinctValues();
string dtCategory = ("SELECT DISTINCT CATEGORY FROM tbl_Maint_Category").fwSqlFillDataTable().fwDistinctValues();
string dtStatus = ("SELECT DISTINCT STATUS FROM tbl_Maint_Status").fwSqlFillDataTable().fwDistinctValues();
string dtUsers = ("SELECT DISTINCT USERNAME FROM tbl_Maint_User").fwSqlFillDataTable().fwDistinctValues();
return JsonConvert.SerializeObject(new
{
Areas = dtArea,
Categories = dtCategory,
Status = dtStatus,
Users = dtUsers
});
}
[WebMethod(EnableSession = true)]
public string fillParams(string users, string categories, string status, string areas)
{
Session["rep-users"] = users;
Session["rep-categories"] = categories;
Session["rep-status"] = status;
Session["rep-areas"] = areas;
return "";
}
}
}
This is the .aspx.cs of export: export.aspx.cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace BORA
{
public partial class export : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
byte[] arr = null;
try
{
clsBORA report = new clsBORA();
arr = report.generateReport();
Response.Clear();
Response.AppendHeader("content-disposition", "attachment; filename=\"BORA Scorecard.xlsx\"");
Response.SetCookie(new HttpCookie("fileDownload", "true"));
Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
Response.BinaryWrite(arr);
//Response.End();
}
catch { /* DO NOTHING */ }
finally
{
if (arr != null) Array.Clear(arr, 0, arr.Length);
GC.Collect();
}
}
}
}
The aspx file named: export.aspx
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="export.aspx.cs" Inherits="BORA.export" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
</div>
</form>
</body>
</html>
Queries are correct, html part is ok, works correctly but it keeps downloading wrong data, aside that, how can I print a byte array?
Anything else I should add?
Also, how can I print that ".fwswlfilldata".
Again, I am new to programming, love it, wanna learn, but sometimes I need help with these things.
Thank you very much
I have an .xml file that contains 30 tables and I want to read all tables and insert the data into a SQL Server database without declaring any variable, means everything is happening dynamically
<person>
<created_by>admin</created_by>
<created_on_timestamp>2014-11-19T14:13:54.000Z</created_on_timestamp>
<date_of_birth>1990-04-04</date_of_birth>
<last_modified_by>admin</last_modified_by>
<last_modified_on>2014-11-21T13:29:49.000Z</last_modified_on>
<logon_user_id>P10621</logon_user_id>
<logon_user_is_active>true</logon_user_is_active>
<logon_user_name>P10621</logon_user_name>
<person_id>3478</person_id>
<person_id_external>P10621</person_id_external>
<personal_informatio>
<last_modified_by>admin</last_modified_by>
<last_modified_on>2014-11-21T14:45:49.000Z</last_modified_on>
<last_name>Singh</last_name>
<marital_status>S</marital_status>
<nationality>IND</nationality>
<salutation>MR</salutation>
<start_date>2014-05-01</start_date>
<personal_information_ind>
<country>IND</country>
<created_by>admin</created_by>
<created_on_timestamp>2014-11-21T13:50:33.000Z</created_on_timestamp>
<custom_string1>hi</custom_string1>
<genericNumber1>22</genericNumber1>
<address_information>
<address1>-0</address1>
<address2>Villa -342,Omax Panorama City</address2>
<address3>-0</address3>
<address4>manphoollamori#gmail.com</address4>
<address5>919828513833</address5>
<address_type>home</address_type>
<city>Bhiwadi</city>
<country>IND</country>
<county>India</county>
<created_by>admin</created_by>
<created_on_timestamp>2014-11-21T15:09:41.000Z</created_on_timestamp>
<end_date>9999-12-31</end_date>
<is_global_model_address>false</is_global_model_address>
<last_m
XmlDocument doc = new XmlDocument();
doc.Load("yourxmlfile.xml");
string databasename = doc.DocumentElement.Name;
foreach (XmlNode node in doc.SelectNodes("/" + databasename + "/*[starts-with(name(), 'SourceTableName')]"))
{
string tablename = node.Attributes["targetTable"].Value;
string Columns = "";
string Values = "";
foreach (XmlNode field in node.SelectNodes("Field"))
{
Columns += (!string.IsNullOrEmpty(Columns) ? ", " : "") + field.Attributes["targetField"].Value;
Values += (!string.IsNullOrEmpty(Values) ? ", " : "") + "'" + field.InnerText + "'";
}
//Generate insert statement
string statement = string.Format("Insert Into {0}.{1} ({2}) Values ({3})",
databasename,
tablename,
Columns,
Values);
Console.WriteLine(statement);
}
I am trying to pass a protected DataRow[] msgArray; from code-behind to the .net page.
msgArray contains rows from a DB table that I selected, when I do Response.Write(msgArray[0]["comment"]) it outputs correctly what I have stored in the comment column in my DB.
The problem is that I cannot do the same in my .net page when I load the page where I do this:
<asp:Panel ID="commentSection" runat="server">
<%= msgArray[0]["comment"] %>
</asp:Panel>
I get a Object reference not set to an instance of an object.
What am I doing wrong ?
This is my code-behind(.cs) :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using MySql.Data.MySqlClient;
namespace Groups
{
public partial class Group : System.Web.UI.Page
{
MySql.Data.MySqlClient.MySqlConnection conn;
MySql.Data.MySqlClient.MySqlCommand cmd;
MySql.Data.MySqlClient.MySqlDataReader reader;
String queryStr;
String gname;
String gtype;
String uname;
DataTable group = new DataTable();
DataTable msg = new DataTable();
protected DataRow[] msgArray;
protected void Page_Load(object sender, EventArgs e)
{
String id = Request.QueryString["id"];
if (id != null)
{
String connString = System.Configuration.ConfigurationManager.ConnectionStrings["GroupsConnString"].ToString();
conn = new MySql.Data.MySqlClient.MySqlConnection(connString);
conn.Open();
queryStr = "SELECT g.*, (SELECT COUNT(id) FROM app_groups.users_groups_leg ugl WHERE ugl.id_group = g.id) as member_count FROM app_groups.groups g WHERE g.id = " + id;
cmd = new MySql.Data.MySqlClient.MySqlCommand(queryStr, conn);
group.Load(reader = cmd.ExecuteReader());
var groupArray = group.AsEnumerable().ToArray();
reader.Close();
int member_count = 0;
int.TryParse(groupArray[0]["member_count"].ToString(), out member_count);
Panel grInfo = new Panel();
grInfo.Controls.Add(new LiteralControl("<br/><div class='panel panel-primary'><div class='panel-heading'><h2>" + groupArray[0]["group_name"] + "</h2></div><div class='panel-body'><span>Categorie: <span class='title'>" + groupArray[0]["group_type"] + "</span></span><br/><span class='membrii'>" + (member_count == 1 ? member_count + " membru" : member_count + " membri") + "</span><br/><span>Fondat pe: " + ConvertUnixTimeStamp(groupArray[0]["founded"].ToString()) + "</span><br/></div></div>"));
groupInfo.Controls.Add(grInfo);
conn.Close();
showComments();
}
}
public static DateTime? ConvertUnixTimeStamp(string unixTimeStamp)
{
return new DateTime(1970, 1, 1).AddSeconds(Convert.ToDouble(unixTimeStamp) + 3600*2);
}
public DataRow[] showComments()
{
String id = Request.QueryString["id"];
if (id != null)
{
String connString = System.Configuration.ConfigurationManager.ConnectionStrings["GroupsConnString"].ToString();
conn = new MySql.Data.MySqlClient.MySqlConnection(connString);
conn.Open();
queryStr = "SELECT gc.* FROM app_groups.group_comments gc WHERE gc.id_group = " + id;
cmd = new MySql.Data.MySqlClient.MySqlCommand(queryStr, conn);
msg.Load(reader = cmd.ExecuteReader());
msgArray = msg.AsEnumerable().ToArray();
reader.Close();
Response.Write(msgArray[0]["comment"]);
/*Panel grComments = new Panel();
grComments.Controls.Add(new LiteralControl(""));
groupInfo.Controls.Add(grComments);*/
}
return msgArray;
}
}
}
Create a new class dataAccess.cs
using System;
using System.Data;
namespace Groups
{
public class dataAccess
{
public List<string> GetComments()
{
String connString = System.Configuration.ConfigurationManager.ConnectionStrings["GroupsConnString"].ToString();
conn = new MySql.Data.MySqlClient.MySqlConnection(connString);
try
{
MySql.Data.MySqlClient.MySqlDataReader reader;
DataTable msg = new DataTable();
conn.Open();
List<string> comments = new List<string>();
queryStr = "SELECT gc.* FROM app_groups.group_comments gc WHERE gc.id_group = " + id;
cmd = new MySql.Data.MySqlClient.MySqlCommand(queryStr, conn);
msg.Load(reader = cmd.ExecuteReader());
foreach(DataRow dr in msg.Rows)
{
comments.Add(dr["comment"]);
}
reader.Close();
return comments;
}
catch (Exception ex)
{
//throw ex;
}
}
}
}
In the ASPX page
<asp:Panel ID="commentSection" runat="server">
<%
var data = Groups.dataAccess.GetComments();
foreach(string c in data)
{
Response.Write("<p>" + c + "</p>");
}
%>
</asp:Panel>
According to ASP.NET Page Life cycle, your method showComments() will be called after the <%= msgArray[0]["comment"] %> part. Hence it won't be available there.
Best way is to have a control like Label in your .aspx page and update the text property from showComments() method.
I have a textarea where I enter some text in multiple lines by pressing enter:
<asp:TextBox ID="tbMessage" runat="server" ClientIDMode="Static"
TextMode="MultiLine" Columns="30" Rows="5"></asp:TextBox>
I save the text from code-behind (MessageText column is of type varchar):
using (SqlCommand qSave = new SqlCommand())
{
qSave.Connection = oCon;
qSave.CommandType = CommandType.Text;
qSave.CommandText = #"INSERT INTO [Db1].[dbo].[Table1] (MessageText) VALUES (#MessageText)";
qSave.Parameters.AddWithValue("#MessageText", tbMessage.Text);
try
{
oCon.Open();
qSave.ExecuteNonQuery();
}
catch (SqlException ce)
{
}
finally
{
oCon.Close();
}
}
I retrieve the column and show it inside a label from code-behind:
public void MyFunction()
{
strSql = #"SELECT * FROM [Db1].[dbo].[Table1]";
using (SqlConnection conn = new SqlConnection(gloString))
{
try
{
// create data adapter
SqlDataAdapter da = new SqlDataAdapter(strSql, conn);
// this will query your database and return the result to your datatable
myDataSet = new DataSet();
da.Fill(myDataSet);
string specific = "";
string generic = "";
string strTemp = "";
foreach (DataRow r in myDataSet.Tables[0].Rows)
{
if (r["MessageText"].ToString().Length <= 65)
{
strTemp = r["MessageText"].ToString();
}
else
{
strTemp = TruncateLongString(r["MessageText"].ToString(), 65) + "...";
}
specific += "<span class='hoverText tooltip' title='" + this.Server.HtmlEncode(r["MessageText"].ToString().Replace("\r\n", "<br />")) + "'>" + this.Server.HtmlEncode(strTemp) + "</span><span class='dvMsgInitHidden'>" + this.Server.HtmlEncode(r["MessageText"].ToString().Replace("\r\n", "<br />")) + "</span><br /><br />";
}
lblMessage.Text = specific;
upMessage.Update();
}
catch (Exception ce)
{
}
}
}
public string TruncateLongString(string str, int maxLength)
{
return str.Substring(0, maxLength);
}
As you can see from the following screenshot the title shows correctly but the message is all jumbled into one line:
Please help me resolve it.
The following CSS takes care of it:
white-space: pre-wrap;
We've made a helper method that simply replaces \r\n, \n, and \r with the HTML break tag for output. We store the text in the database with the raw \r \n characters, and during edit, TextArea honors the line break naturally. Its only when showing on the "details page" in a span, that the conversion to a HTML break tag should be done.
If you need to store formating in ddbb, you can use rtf or html tags for this. Rtf could be more suited for desktop apps, in your case, you'll need to store html tags among the text (p, br, etc)
I am new to asp.net, and what I want to know is how to bind data directly into a custom div
without using things such as data grid or any other thing, let's say I want to bind a description for something stored in my sql DB.
In PHP i used to do this:
<p>
<?php echo $row_RecordSetName['col']; ?>
</p>
But how to do in asp.net using C# in a webform?
I tried to do it in a dataset thing like so but it keeps giving errors:
<p>
<%= Dataset.DB[0].colNAME.ToString() %>
</p>
as well as i tried doing the following stupid way :
try
{
for (int i = 1; i < 7; i++)
{
SqlConnection cn = new SqlConnection("Data Source=server;Initial Catalog=db;Integrated Security=True");
SqlCommand cmd = new SqlCommand("SELECT * FROM mallsdb where mall_un='" + i + "'", cn);
SqlDataAdapter da = new SqlDataAdapter(cmd);
MallsDS tds = new MallsDS();
da.Fill(tds, tds.Tables[0].TableName);
string MallPIC = Convert.ToString(tds.mallsdb[0].mall_pic);
string MallNAME = Convert.ToString(tds.mallsdb[0].mall_name);
string MallUn = Convert.ToString(tds.mallsdb[0].mall_un);
string MallDESP;
string check_desp = Convert.ToString(tds.mallsdb[0].mall_desp);
if (check_desp.Length < 50)
{
MallDESP = check_desp;
}
else
{
string under = check_desp.Substring(0, 30);
MallDESP = under + "....";
}
Result[i] = "<div class='malls'>" + "<img src='images/" + MallPIC + "' width='250' height='250' />" + "<a class='namer' href='malls_private.aspx?mall_un=" + MallUn + "'><h1>" + MallNAME + "</h1></a><p>" + MallDESP + "</p></div>";
}
}
catch (Exception ex)
{
Response.Write("Error:" + ex.ToString());
}
Label1.Text = Result[1];
Label2.Text = Result[2];
Label3.Text = Result[3];
Label4.Text = Result[4];
Label5.Text = Result[5];
Label6.Text = Result[6];
In C#, you can do something like <div runat='server' id='divWhateverDiv'> in the aspx and then in the actual C# code (not in the aspx itself) you can reference the div element as a normal C# variable by its id, and do something like divWhateverDiv.innerHTML = "whatever"; Visual Studio's intellisense will help you with the actual capitialization of the members and such. What you're trying to do is more like old asp than asp.net
thanks friends and in the following is the answer to my question, as i read about it in microsoft MSDN.
<%# Page language="c#" %>
<%# Import Namespace="System.Data" %>
<%# Import Namespace="System.Data.SqlClient" %>
<script runat="server">
void Page_Load(Object sender, EventArgs e)
{
SqlConnection cnn = new
SqlConnection("server=(local);database=pubs;Integrated Security=SSPI");
SqlDataAdapter da = new SqlDataAdapter("select * from authors", cnn);
DataSet ds = new DataSet();
da.Fill(ds, "authors");
Repeater1.DataSource = ds.Tables["authors"];
Repeater1.DataBind();
}
</script>
<html>
<body>
<form id="WebForm2" method="post" runat="server">
<asp:Repeater id="Repeater1" runat="server">
<ItemTemplate>
<%# DataBinder.Eval(Container.DataItem,"au_id") %><br>
</ItemTemplate>
</asp:Repeater>
</form>
</body>
</html>