Exporting data from a table in SQL Server using ASP.Net - asp.net

I am using Visual Studio 2010 and SQL Server 2008. I need to create a XML file which looks like:
<cat>
<name> "Categories"</name>
<link> "link"</link>
</cat>
The Categories and link values should be added from the database.
I have tried everything but I cannot get it to work. DO I have to create a XML file in ASP to do this?
These values are in the same table but there are other columns in the table as well.
My code looks something like this:
SqlCommand sqlcmd = new SqlCommand();
//sqlcmd.CommandText = "Select * from Categories";
DataSet ds = new DataSet();
System.Data.SqlClient.SqlDataAdapter da = new System.Data.SqlClient.SqlDataAdapter("Select * from Categories", "Data Source=something;Initial Catalog=My Database;Integrated Security=True");
da.Fill(ds);
int rows;
rows = ds.Tables[0].Rows.Count;
int i;
for (i = 0; i <= rows - 1; i++)
{
string Categories = ds.Tables[0].Rows[i].ItemArray[0].ToString();
string address = "https://www.something.com/";
string link = address + ds.Tables[0].Rows[i].ItemArray[1].ToString();
}
ds.WriteXml(#"c:\output.xml", XmlWriteMode.WriteSchema);
Can someone please give me a detailed solution to this problem.
Thank you

SqlCommand sqlcmd = new SqlCommand();
sqlcmd.CommandText = "Select * from Categories";
DataSet ds = new DataSet();
System.Data.SqlClient.SqlDataAdapter da = new System.Data.SqlClient.SqlDataAdapter("Select * from Categories", "Data Source=something;Initial Catalog=My Database;Integrated Security=True");
da.Fill(ds);
int rows;
rows = ds.Tables[0].Rows.Count;
int i;
xmlwr.WriteStartElement("Cat");
for (i = 0; i <= rows - 1; i++)
{
xmlwr.WriteStartElement("name");
xmlwr.xmlwr.WriteString(ds.Tables[0].Rows[i].ItemArray[0].ToString());
xmlwr.WriteEndElement;
xmlwr.WriteStartElement("link");
xmlwr.xmlwr.WriteString(ds.Tables[0].Rows[i].ItemArray[1].ToString());
xmlwr.WriteEndElement;
}
xmlwr.WriteEndElement;
ds.WriteXml(#"c:\output.xml", XmlWriteMode.WriteSchema);

Related

How to store a select query result ( one result ) to a variable using executescalar() ? ( ASP.NET )

i have to store a select query result in a variable .i'm new in asp.net . i used executescalar but it doesn't work. i try many times but i failed here my last try :
using (SqlConnection sqlConnection = new SqlConnection())
{
var connetionString = ConfigurationManager.ConnectionStrings["connections"].ToString();
sqlConnection.ConnectionString = connetionString;
string sql = "Select sum((prime_comptant+10)*0.12) from mvt_garantie_quittance where numero_quittance='" + numQuittance + "'";
SqlDataAdapter adapter = new SqlDataAdapter(sql, sqlConnection);
DataSet dataset = new DataSet();
adapter.Fill(dataset);
string result = dataset.Tables[0].ToString();
}
Can you fix the code to me? i have to store the result in a variable
string sql = "Select sum((prime_comptant+10)*0.12) from mvt_garantie_quittance where numero_quittance='" + numQuittance + "'";
var connetionString = ConfigurationManager.ConnectionStrings["connections"].ToString();
string result = null;
using (SqlConnection conn = new SqlConnection(connetionString))
{
SqlCommand cmd = new SqlCommand(sql, conn);
conn.Open();
result = cmd.ExecuteScalar().ToString();
}

Get Distinct data from datatable present in webservices using linq

I want to get only single row from multiple rows with same projectname from the datatable.(Eg. if we have two rows with same projectname,the datatable should be loaded with the only one row and neglect the other one.).I have been using webservices which has the datatable.
I want to achieve this functionality using linq.
I have pasted my code for datatable.Pls help me with working code.
[WebMethod]
public DataTable Get()
{
int a = 0;
cmd = con.CreateCommand();
con.Open();
cmd = con.CreateCommand();
cmd.CommandText = " Select PROJECTNAME,COMPANY,PROJECTSTATUS,STARTEDIN,COMPLETEDIN FROM CMPPROJECT WHERE STATUS ='" + a + "'";
using (OracleDataAdapter sda = new OracleDataAdapter())
{
cmd.Connection = con;
sda.SelectCommand = cmd;
using (DataTable dt = new DataTable())
{
dt.TableName = "CMPPROJECT";
sda.Fill(dt);
return dt;
}
}
}
You can create a DataView object which has a method ToTable in which you can pass true to parameter distinct to select distinct rows. But this has no sense to me. I would do this directly in a select query:
DataTable d = new DataTable("CMPPROJECT");
d.Columns.Add("PROJECTNAME");
d.Columns.Add("COMPANY");
d.Rows.Add(1, 1);
d.Rows.Add(1, 1);
d.Rows.Add(2, 2);
d = new DataView(d).ToTable("CMPPROJECT", true, "PROJECTNAME", "COMPANY");
Here is `linq solution:
var select = (from a in d.AsEnumerable()
select new { c1 = a["PROJECTNAME"], c2 = a["COMPANY"] }).Distinct().ToList();
d.Clear();
foreach (var item in select)
d.Rows.Add(item.c1, item.c2);

not able to insert data in table using datatable

i have one table having 3 rows and i am trying to insert data into first two rows using data table but it is inserting data like this , instead of inserting in first two row it is inserting in other rows
price qty total
--------------------
5 10 -
5 12 -
- - 50
- - 60
but i wants
price qty total
--------------------
5 10 50
5 12 60
i have used following code for selecting data from table than inserting data into table,it is showing data correctly but just inserting in wrong rows
int sp;
public DataTable bind1()
{
SqlConnection con = new SqlConnection("cnnection");
con.Open();
SqlCommand cmd;
cmd = new SqlCommand("select * from [order]", con);
DataTable dt = new DataTable();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);
con.Close();
return dt;
}
public DataTable bind2()
{
SqlConnection con = new SqlConnection("cnnection");
con.Open();
SqlCommand cmd;
cmd = new SqlCommand("insert into [order](total) values(#total)", con);
cmd.Parameters.AddWithValue("#total", sp);
DataTable dt = new DataTable();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);
con.Close();
return dt;
}
public void gbind()
{
DataTable dt = new DataTable();
dt = bind1();
DataTable dt1 = new DataTable();
DataColumn dc = new DataColumn("total");
dt1.Columns.Add(dc);
foreach(DataRow drow in dt.Rows)
{
int s1 = Convert.ToInt16(drow["price"]);
int s2 = Convert.ToInt16(drow["qty"]);
int s3 = s1 * s2;
DataRow dr = dt1.NewRow();
dr["total"] = s3;
dt1.Rows.Add(dr);
}
foreach (DataRow row in dt1.Rows)
{
string s1 = row["total"].ToString();
for (int i = 0; i < dt.Rows.Count; i++)
{
sp = Convert.ToInt16(s1);
dt = bind2();
}
}
i have tried like this also but still same problem
public void gbind()
{
DataTable dt = new DataTable();
dt = bind1();
foreach (DataRow drow in dt.Rows)
{
int s1 = Convert.ToInt16(drow["price"]);
int s2 = Convert.ToInt16(drow["qty"]);
int s3 = s1 * s2;
drow["total"] = s3;
sp = s3;
dt = bind2();
}
}
In your forEach loop in the gbind method, I don't think you should be adding a new row for "total", it would need to be a column. And dt1.Rows.Add(dr) should be dt1.Columns.Add(dr). Try rewriting your code to add a column instead. Let me know if that helps any.
Comment these two lines in your code. Remove the code to add extra rows. You just need to update the column value.
foreach(DataRow drow in dt.Rows)
{
int s1 = Convert.ToInt16(drow["price"]);
int s2 = Convert.ToInt16(drow["qty"]);
int s3 = s1 * s2;
//DataRow dr = dt1.NewRow();
dr["total"] = s3;
//dt1.Rows.Add(dr);
}

Why insert statement generates 2 rows?

I dont know why, but when I do an insert statement in my project, its generate 2 indentical rows instead of makeing just one.
why is that ?
this is my code :
if (ListBox.Items.Count != 0)
{
string username = Session["Session"].ToString();
con = new SqlConnection("Data Source=MICROSOF-58B8A5\\SQL_SERVER_R2;Initial Catalog=Daniel;Integrated Security=True");
con.Open();
string knowWhichOne = "SELECT ID FROM Users WHERE Username='" + UserOrGuest.Text + "'";
SqlCommand comm = new SqlCommand(knowWhichOne, con);
int userID = (Int32)comm.ExecuteScalar();
knowWhichOne = "SELECT ClassID FROM Users WHERE Username='" + UserOrGuest.Text + "'";
comm = new SqlCommand(knowWhichOne, con);
int classID = (Int32)comm.ExecuteScalar();
knowWhichOne = "SELECT SchoolID FROM Users WHERE Username='"+UserOrGuest.Text + "'";
comm = new SqlCommand(knowWhichOne, con);
int schoolID = (Int32)comm.ExecuteScalar();
if (RadioWords.Checked == true)
{
game = 1;
}
else
{
game = 2;
}
string arr = "";
for (int i = 0; i < ListBox.Items.Count; i++)
{
arr += ListBox.Items[i] +",";
}
string sqlqueryString = "INSERT INTO HistoryOfGames (GameID, UserID, LengthOfArray, NumberOfErrors, ClassID, SchoolID,Arrayarray) VALUES (#GameID, #UserID, #LengthOfArray, #NumberOfErrors, #ClassID, #SchoolID, #Arrayarray);" + "SELECT SCOPE_IDENTITY()";
SqlCommand commandquery = new SqlCommand(sqlqueryString, con);
commandquery.Parameters.AddWithValue("GameID", game);
commandquery.Parameters.AddWithValue("UserID", userID);
commandquery.Parameters.AddWithValue("LengthOfArray", HowMany.Text);
commandquery.Parameters.AddWithValue("NumberOfErrors", 0);
commandquery.Parameters.AddWithValue("ClassID", classID);
commandquery.Parameters.AddWithValue("SchoolID", schoolID);
commandquery.Parameters.AddWithValue("Arrayarray", arr);
commandquery.ExecuteNonQuery();
int IdOfRecentHistoryGame = (int)(decimal)commandquery.ExecuteScalar();
con.Close();
Response.Redirect("NowPlay.aspx?ID="+ IdOfRecentHistoryGame);
}
You're running it twice, ExecuteNonQuery() and ExecuteScalar(). Get rid of the ExecuteNonQuery().
you do
commandquery.ExecuteNonQuery();
then right after
int IdOfRecentHistoryGame = (int)(decimal)commandquery.ExecuteScalar();
you do execute it twice
and don't forget to check for sql injection in your code...
I'd check two things:
see how many times this statement is executed (try setting a breakpoint to verify that the code is only run once)
see if there are any triggers in the database that might cause an extra record to be inserted
I had the same problem,I handled it this way.not professional but it works:
Dim x As Boolean = True
If x = True Then
here goes your code to insert to database.
End If
x = False

Regarding binding array to gridview

Hi
I have created session array :
int[] a = (int[])Session["values"];
Now i have to bind this value to my gridview. I have one column (boundfield in my gridview) in gridview.
I used code to bind array to gridview as follows, but its giving last value only as i want all the values to bind :
for (int i = 0; i < a.Length; i++)
{
str = "select * from Quest_Info where Quest_id='" + a[i] + "' order by Quest_id";
SqlDataAdapter da2 = new SqlDataAdapter(str, sqlconn);
ds2 = new DataSet();
da2.Fill(ds2, "Result");
reviewgrid.DataSource = ds2;
reviewgrid.DataBind();
}
Which code will work for this?
Asp.net, c#
Thank You.
Your code may not work because you are trying to bind gridview in the for loop which keep repeating and will result to bind only one last array id in the end.
You may try to prepare query out front before binding the gridview as example below.
string questIds = string.Empty;
for (int i = 0; i < a.Length; i++)
{
if (questIds.Length > 0)
questIds += ", ";
questIds += a[i];
}
string strSQL = "select * from Quest_Info where Quest_id IN ("+ questIds + ") order by Quest_id";
SqlDataAdapter da2 = new SqlDataAdapter(str, sqlconn);
ds2 = new DataSet();
da2.Fill(ds2, "Result");
reviewgrid.DataSource = ds2;
reviewgrid.DataBind();

Resources