How to display datatable value into text box - c#

I want to show my datatable value into text box with including headers
I tried something like this not sure its correct or not ?
private void Button16_Click(object sender, EventArgs e)
{
textBox5.Text = string.Empty;
if (checkedListBox1.CheckedItems.Count > 0)
{
string strSQLConn = "Server =" + textBox1.Text + "; Initial Catalog =" + textBox2.Text + "; User ID =" + textBox3.Text + "; Password = " + textBox4.Text + ";";
SqlConnection SQLConn = new SqlConnection(strSQLConn);
SQLConn.Open();
foreach (var item in checkedListBox1.CheckedItems)
{
DataRowView row = item as DataRowView;
SqlCommand SQLCmd = new SqlCommand("select TABLE_NAME, COLUMN_NAME, DATA_TYPE, CHARACTER_MAXIMUM_LENGTH, IS_NULLABLE from INFORMATION_SCHEMA.COLUMNS where TABLE_NAME = '" + row["Table_Name"] + "' ", SQLConn);
SQLCmd.CommandType = CommandType.Text;
SqlDataAdapter Da = new SqlDataAdapter(SQLCmd);
DataTable dt = new DataTable();
Da.Fill(dt);
if (dt.Rows.Count > 0)
{
textBox5.Text = dt.Rows[0]["TABLE_NAME"].ToString();
textBox5.Text = dt.Rows[0]["COLUMN_NAME"].ToString();
textBox5.Text = dt.Rows[0]["DATA_TYPE"].ToString();
textBox5.Text = dt.Rows[0]["CHARACTER_MAXIMUM_LENGTH"].ToString();
textBox5.Text = dt.Rows[0]["IS_NULLABLE"].ToString();
}
}
}

I believe you are trying to append instead of overriding the text. Therefore,
textBox5.Text = dt.Rows[0]["TABLE_NAME"].ToString() + ", ";
textBox5.Text += dt.Rows[0]["COLUMN_NAME"].ToString()+ ", ";
textBox5.Text += dt.Rows[0]["DATA_TYPE"].ToString()+ ", ";
textBox5.Text += dt.Rows[0]["CHARACTER_MAXIMUM_LENGTH"].ToString()+ ", ";
textBox5.Text += dt.Rows[0]["IS_NULLABLE"].ToString();
To go through all rows
for (int i = 0; i < dt.Rows.Count; i++)
{
textBox5.Text = dt.Rows[i]["TABLE_NAME"].ToString() + ", ";
textBox5.Text += dt.Rows[i]["COLUMN_NAME"].ToString()+ ", ";
textBox5.Text += dt.Rows[i]["DATA_TYPE"].ToString()+ ", ";
textBox5.Text += dt.Rows[i]["CHARACTER_MAXIMUM_LENGTH"].ToString()+ ", ";
textBox5.Text += dt.Rows[i]["IS_NULLABLE"].ToString();
}
Moreover, I suggest to scope your connection, command and adapter in using(so system can close/dispose them automatically) and use
SqlParameter instead of string concatenation(to prevent potential SQL injection)
using (SqlConnection SQLConn = new SqlConnection(strSQLConn))
{
SQLConn.Open();
foreach (var item in checkedListBox1.CheckedItems)
{
DataRowView row = item as DataRowView;
using (SqlCommand SQLCmd = new SqlCommand("select TABLE_NAME, COLUMN_NAME, DATA_TYPE, CHARACTER_MAXIMUM_LENGTH, IS_NULLABLE from INFORMATION_SCHEMA.COLUMNS where TABLE_NAME = #tableName ", SQLConn))
{
SQLCmd.Parameters.AddWithValue("tableName", row["Table_Name"]);
using (SqlDataAdapter Da = new SqlDataAdapter(SQLCmd))
{
DataTable dt = new DataTable();
Da.Fill(dt);
// rest of the code
}
}
}
}
You can retrieve columns from DataTable.Columns and if you too want to attach to the TextBox then sample as below
textBox5.Text += string.Join(",", dt.Columns.OfType<DataColumn>().Select(col => col.ColumnName));

Related

System.Data.SqlClient.SqlException: 'Invalid column name 'P1000'.'

Can anybody help me? Why am I getting this error?
If I remove the 'P' from the prod_id which left only number, it can work but if I add alphabet, it says "Invalid column name".
I already added .ToString() to it, but why it still can't take varchar and only take int.
Here is my code
public partial class AddtoCart : System.Web.UI.Page
{
SqlConnection conn = new SqlConnection(Global.cs);
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
if (Session["Username"] == null)
{
Response.Redirect("Authentication.aspx");
}
// Adding product to Gridview
Session["addproduct"] = "false";
DataTable dt = new DataTable();
DataRow dr;
dt.Columns.Add("sno");
dt.Columns.Add("Id");
dt.Columns.Add("Pname");
dt.Columns.Add("Pimage");
dt.Columns.Add("Pprice");
dt.Columns.Add("Pquantity");
dt.Columns.Add("Ptotal");
if (Request.QueryString["Id"] != null)
{
if (Session["buyitems"] == null)
{
dr = dt.NewRow();
SqlConnection conn = new SqlConnection(Global.cs);
SqlDataAdapter da = new SqlDataAdapter("select * from Product2 where prod_id=" + Request.QueryString["Id"] , conn);
DataSet ds = new DataSet();
da.Fill(ds);
dr["sno"] = 1;
dr["Id"] = ds.Tables[0].Rows[0]["prod_id"].ToString();
dr["Pname"] = ds.Tables[0].Rows[0]["prod_name"].ToString();
dr["Pimage"] = ds.Tables[0].Rows[0]["prod_img"].ToString();
dr["Pprice"] = ds.Tables[0].Rows[0]["prod_price"].ToString();
dr["Pquantity"] = Request.QueryString["quantity"];
int price = Convert.ToInt32(ds.Tables[0].Rows[0]["prod_price"].ToString());
int Quantity = Convert.ToInt16(Request.QueryString["quantity"].ToString());
int TotalPrice = price * Quantity;
dr["Ptotal"] = TotalPrice;
dt.Rows.Add(dr);
conn.Open();
SqlCommand cmd = new SqlCommand("insert into Cart values('" + dr["sno"] + "','" + dr["Id"] + "','" + dr["Pname"] + "','" + dr["Pimage"] + "','" + dr["Pprice"] + "','" + dr["Pquantity"] + "','" + dr["Ptotal"] + "','" + Session["Username"].ToString() + "')", conn);
cmd.ExecuteNonQuery();
conn.Close();
GridView1.DataSource = dt;
GridView1.DataBind();
Session["buyitems"] = dt;
Button1.Enabled = true;
GridView1.FooterRow.Cells[5].Text = "Total Amount";
GridView1.FooterRow.Cells[6].Text = grandtotal().ToString();
Response.Redirect("AddtoCart.aspx");
}
else
{
dt = (DataTable)Session["buyitems"];
int sr;
sr = dt.Rows.Count;
dr = dt.NewRow();
SqlConnection conn = new SqlConnection(Global.cs);
SqlDataAdapter da = new SqlDataAdapter("select * from Product2 where prod_id=" + Request.QueryString["id"], conn);
DataSet ds = new DataSet();
da.Fill(ds);
dr["sno"] = sr + 1;
dr["Id"] = ds.Tables[0].Rows[0]["prod_id"].ToString();
dr["Pname"] = ds.Tables[0].Rows[0]["prod_name"].ToString();
dr["Pimage"] = ds.Tables[0].Rows[0]["prod_img"].ToString();
dr["Pprice"] = ds.Tables[0].Rows[0]["prod_price"].ToString();
dr["Pquantity"] = Request.QueryString["quantity"];
int price = Convert.ToInt32(ds.Tables[0].Rows[0]["prod_price"].ToString());
int Quantity = Convert.ToInt16(Request.QueryString["quantity"].ToString());
int TotalPrice = price * Quantity;
dr["Ptotal"] = TotalPrice;
dt.Rows.Add(dr);
conn.Open();
SqlCommand cmd = new SqlCommand("insert into Cart values('" + dr["sno"] + "','" + dr["Id"] + "','" + dr["Pname"] + "','" + dr["Pimage"] + "','" + dr["Pprice"] + "','" + dr["Pquantity"] + "','" + dr["Ptotal"] + "','" + Session["Username"].ToString() + "')", conn);
cmd.ExecuteNonQuery();
conn.Close();
GridView1.DataSource = dt;
GridView1.DataBind();
Session["buyitems"] = dt;
Button1.Enabled = true;
GridView1.FooterRow.Cells[5].Text = "Total Amount";
GridView1.FooterRow.Cells[6].Text = grandtotal().ToString();
Response.Redirect("AddtoCart.aspx");
}
}
else
{
dt = (DataTable)Session["buyitems"];
GridView1.DataSource = dt;
GridView1.DataBind();
if (GridView1.Rows.Count > 0)
{
GridView1.FooterRow.Cells[5].Text = "Total Amount";
GridView1.FooterRow.Cells[6].Text = grandtotal().ToString();
}
}
}
if (GridView1.Rows.Count.ToString() == "0")
{
Button3.Enabled = false;
Button1.Enabled = false;
}
else
{
Button3.Enabled = true;
Button1.Enabled = true;
}
}
// 2.Calculating Final Price
public int grandtotal()
{
DataTable dt = new DataTable();
dt = (DataTable)Session["buyitems"];
int nrow = dt.Rows.Count;
int i = 0;
int totalprice = 0;
while (i < nrow)
{
totalprice = totalprice + Convert.ToInt32(dt.Rows[i]["Ptotal"].ToString());
i = i + 1;
}
return totalprice;
}
// 4. Deleting Row From Cart
protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
DataTable dt = new DataTable();
dt = (DataTable)Session["buyitems"];
for (int i = 0; i <= dt.Rows.Count - 1; i++)
{
int sr;
int sr1;
string qdata;
string dtdata;
sr = Convert.ToInt32(dt.Rows[i]["sno"].ToString());
TableCell cell = GridView1.Rows[e.RowIndex].Cells[0];
qdata = cell.Text;
dtdata = sr.ToString();
sr1 = Convert.ToInt32(qdata);
TableCell prID = GridView1.Rows[e.RowIndex].Cells[1];
if (sr == sr1)
{
dt.Rows[i].Delete();
dt.AcceptChanges();
conn.Open();
SqlCommand cmd = new SqlCommand("Delete top (1) from Cart where product_id='" + prID.Text + "' and username= '" + Session["username"] + "' ", conn);
cmd.ExecuteNonQuery();
conn.Close();
//Item Has Been Deleted From Shopping Cart
break;
}
}
// 5. Setting SNo. after deleting Row item from cart
for (int i = 1; i <= dt.Rows.Count; i++)
{
dt.Rows[i - 1]["sno"] = i;
dt.AcceptChanges();
}
Session["buyitems"] = dt;
Response.Redirect("AddtoCart.aspx");
}
// 6. Button Click
protected void Button1_Click(object sender, EventArgs e)
{
bool isTrue = false;
DataTable dt = (DataTable)Session["buyitems"];
for (int i = 0; i <= dt.Rows.Count - 1; i++)
{
//SqlConnection conn = new SqlConnection(Global.cs);
//conn.Open();
//SqlCommand cmd = new SqlCommand("insert into Cart(sno,product_id,product_name,product_price,product_quantity,username) values('" + dt.Rows[i]["sno"] + "','" + dt.Rows[i]["Id"] + "','" + dt.Rows[i]["Pname"] + "','" + dt.Rows[i]["Pprice"] + "','" + dt.Rows[i]["Pquantity"] + "','" + Session["Username"] + "')", conn);
//cmd.ExecuteNonQuery();
//conn.Close();
int pId = Convert.ToInt16(dt.Rows[i]["Id"]);
int pQuantity = Convert.ToInt16(dt.Rows[i]["Pquantity"]);
SqlDataAdapter sda = new SqlDataAdapter("Select stock_count, prod_name from Product2 where prod_id='" + pId + "' ", conn);
DataTable dtble = new DataTable();
sda.Fill(dtble);
int quantity = Convert.ToInt16(dtble.Rows[0][0]);
if(quantity == 0)
{
string pName = dtble.Rows[0][1].ToString();
string msg = "" + pName + " is not in Stock";
Response.Write("<script>alert('" + msg + "');</script>");
isTrue = false;
}
}
if (GridView1.Rows.Count.ToString() == "0")
{
Response.Write("<script>alert('Your Cart is Empty. You cannot place an Order');</script>");
}
else
{
if (isTrue == true)
{
Response.Redirect("Checkout2.aspx");
}
}
// If Session is Null Redirecting to login else Placing the order
if (Session["Username"] == null)
{
Response.Redirect("Authentication.aspx");
}
else
{
Response.Redirect("Checkout2.aspx");
}
}
public void clearCart()
{
conn.Open();
SqlCommand cmd = new SqlCommand("Delete from Cart where username='" + Session["Username"] + "' ", conn);
cmd.ExecuteNonQuery();
conn.Close();
Response.Redirect("AddtoCart.aspx");
}
protected void Button3_Click(object sender, EventArgs e)
{
Session["buyitems"] = null;
clearCart();
}
}
This is the database table
CREATE TABLE [dbo].[Product2]
(
[prod_id] VARCHAR(6) NOT NULL,
[prod_name] VARCHAR(50) NOT NULL,
[prod_price] FLOAT(53) NOT NULL,
[prod_desc] VARCHAR(120) NOT NULL,
[prod_img] NVARCHAR(MAX) NOT NULL,
[prod_cat] VARCHAR(6) NOT NULL,
[stock_count] INT NULL,
[weight] DECIMAL(9, 2) NULL,
[width] DECIMAL(9, 2) NULL,
[length] DECIMAL(9, 2) NULL,
[height] DECIMAL(9, 2) NULL,
[shipping_fee] DECIMAL(9, 2) NOT NULL,
[created_at] DATETIME NOT NULL,
[updated_at] DATETIME NULL,
[prod_status] NVARCHAR(MAX) NULL,
PRIMARY KEY CLUSTERED ([prod_id] ASC),
CONSTRAINT [FK_Product2_ToTable]
FOREIGN KEY ([prod_cat]) REFERENCES [dbo].[Category] ([cat_id])
);
The way you pass the query could lead to SQL Injection.
SqlDataAdapter da = new SqlDataAdapter("select * from Product2 where prod_id=" + Request.QueryString["Id"] , conn);
I expect the final query you want to achieve is
select * from Product2 where prod_id=`P100`
But after revise your code if you do concatenate with 'P' in your query, you will get:
select * from Product2 where prod_id=P100
In which this will return result:
Invalid column name 'P100'
String concatenation into query is dangerous that possible break your query.
You need to create a SqlCommand variable and pass it to the SqlDataAdapter.
And also use SqlParameter to pass the parameter value.
SqlCommand cmd = new SqlCommand("select * from Product2 where prod_id = #Prod_ID", con);
cmd.Parameters.Add("#Prod_ID", SqlDbType.Varchar, 6).Value = "P" + Request.QueryString["id"].ToString;
After create and initialize SqlCommand, then you pass it into SqlDataAdpater as below
SqlDataAdapter da = new SqlDataAdapter(cmd);
Additional recommendation:
Use using block for your SqlConnection, SqlCommand and SqlDataAdapter as these (implemented with IDisposable interface) will automatically dispose the resources once the process is ended or exception is triggered.
DataSet ds = new DataSet();
using (SqlConnection conn = new SqlConnection(Global.cs))
{
using (SqlCommand cmd = new SqlCommand("select * from Product2 where prod_id = #Prod_ID", con))
{
cmd.Parameters.Add("#Prod_ID", SqlDbType.Varchar, 6).Value = "P" + Request.QueryString["id"].ToString;
using (SqlDataAdapter da = new SqlDataAdapter(cmd))
{
da.Fill(ds);
}
}
}
Updated answer with credited to #Tim Schmelter's suggestion
For Using declarations in C#8.0, you are not required to add scope for the using block.
A using declaration is a variable declaration preceded by the using keyword. It tells the compiler that the variable being declared should be disposed at the end of the enclosing scope.
DataSet ds = new DataSet();
using SqlConnection conn = new SqlConnection(Global.cs);
using SqlCommand cmd = new SqlCommand("select * from Product2 where prod_id = #Prod_ID", con);
cmd.Parameters.Add("#Prod_ID", SqlDbType.Varchar, 6).Value = "P" + Request.QueryString["id"].ToString;
using SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(ds);

Fill an array with sql query

Is there anyway to fill an multidimensional array with a sql query? My sql query results on a pivot table. As you can see, I want so make some sums (for Total Column and Total Row) and I want to know the best way to make that sums and percentages in that table.. I said multidimensional array because it could be easier. The code below works but I want to know how can I choose the rows and columns to make the sums. I'm using ASP.NET C#
protected void Button1_Click(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection("Data Source=****;Initial Catalog=***;User=sa;password=***");
//query for all specialities
string specstring = "SELECT Speciality.Shortname, SUM(1) as contar " +
"FROM DoctorEnterpriseDetails INNER JOIN " +
"Speciality ON DoctorEnterpriseDetails.Speciality1 = Speciality.SpecialityId INNER JOIN " +
" GroupType ON DoctorEnterpriseDetails.GroupId = GroupType.GroupId " +
" WHERE (DoctorEnterpriseDetails.EnterpriseId = 48) " +
" GROUP BY Speciality.Shortname ";
SqlCommand command = new SqlCommand(specstring, conn);
command.Connection.Open();
SqlDataAdapter myDataAdapter = new SqlDataAdapter();
myDataAdapter.SelectCommand = command;
// Adds rows in the DataSet
//DataSet myDataSet = new DataSet();
DataTable specstringtable = new DataTable();
myDataAdapter.Fill(specstringtable);
specstring = "";
for (int i = 0; i < specstringtable.Rows.Count; i++)
{
if (specstring == "")
{
specstring = "[" + specstringtable.Rows[i][0] + "]".ToString();
}
else
{
specstring = specstring + ", " + "[" + specstringtable.Rows[i][0] + "]";
}
}
//GroupGrid.DataSource = cobtable;
//GroupGrid.DataBind();
command.Connection.Close();
////query for pivot table
string querystring = "SELECT Description AS Categoria, " + specstring +
"FROM (SELECT GroupType.Description, Speciality.Shortname, SUM(1) AS contar, GroupType.GroupId " +
"FROM DoctorEnterpriseDetails INNER JOIN " +
"Speciality ON DoctorEnterpriseDetails.Speciality1 = Speciality.SpecialityId INNER JOIN " +
"GroupType ON DoctorEnterpriseDetails.GroupId = GroupType.GroupId " +
"WHERE (DoctorEnterpriseDetails.EnterpriseId = 48) " +
"GROUP BY GroupType.Description, Speciality.Shortname, DoctorEnterpriseDetails.GroupId, GroupType.GroupId) as ps " +
"PIVOT (SUM(contar) FOR Shortname IN (" + specstring + ")) pvt " +
"ORDER BY GroupId; ";
////Response.Write(querystring);
SqlCommand command2 = new SqlCommand(querystring, conn);
command2.Connection.Open();
SqlDataAdapter myDataAdapter2 = new SqlDataAdapter();
myDataAdapter2.SelectCommand = command2;
// Adds rows in the DataSet
//DataSet myDataSet2 = new DataSet();
DataTable cobtable = new DataTable();
myDataAdapter2.Fill(cobtable);
DataColumn cl = cobtable.Columns.Add("Total");
cobtable.Columns["Total"].SetOrdinal(1);
DataRow dr;
dr = cobtable.NewRow();
dr["Categoria"] = "Total";
cobtable.Rows.InsertAt(dr, 0);
dr = cobtable.NewRow();
dr["Categoria"] = "";
cobtable.Rows.InsertAt(dr, 1);
dr = cobtable.NewRow();
dr["Categoria"] = "%";
cobtable.Rows.InsertAt(dr, 3);
dr = cobtable.NewRow();
dr["Categoria"] = "";
cobtable.Rows.InsertAt(dr, 4);
dr = cobtable.NewRow();
dr["Categoria"] = "%";
cobtable.Rows.InsertAt(dr, 6);
dr = cobtable.NewRow();
dr["Categoria"] = "";
cobtable.Rows.InsertAt(dr, 7);
dr = cobtable.NewRow();
dr["Categoria"] = "%";
cobtable.Rows.InsertAt(dr, 9);
GroupGrid.DataSource = cobtable;
GroupGrid.DataBind();
}
c

Update dynamically created textbox

I have created this update function but I am gettng "SelectCommand.Connection property has not been initialized" error.Can anyone help me for this.My code is:
public void Update_Click(object sender, EventArgs e)
{
Button b = sender as Button;
b.ForeColor = Color.Blue;
b.Font.Bold = true;
string strTableName = Request.QueryString["table"];
DataTable dt = new DataTable();
DataTable dtColumn=new DataTable();
MySqlConnection sQLcONN = new MySqlConnection("connection");
sQLcONN.Open();
// MySqlCommand sqlcolum=new MySqlCommand("SELECT *FROM information_schema.columns WHERE table_name ="+strTableName);
// MySqlDataAdapter sqlDa1=new MySqlDataAdapter(sqlcolum);
// sqlDa1.Fill(dtColumn);
// MySqlCommand sqlCmd = new MySqlCommand("update " + strTableName + "set " + dtColumn.Rows[introws]["column_name"] + "='" + "txtTextbox" + dt.Rows[introws][0].ToString() + "' where " + dtColumn.Rows[introws]["column_name"] + "=" + dt.Rows[introws][0], sQLcONN);
MySqlCommand sqlCmd = new MySqlCommand("update " + strTableName + "set " + dtColumn.Rows[introws]["column_name"] + "=#value1 where " + dtColumn.Rows[introws]["column_name"] + "=#value2", sQLcONN);
sqlCmd.Parameters.AddWithValue("#value1", "txtTextBox + dt.Rows[introws][0].ToString()");
sqlCmd.Parameters.AddWithValue("#value2",dt.Rows[introws][0]);
MySqlDataAdapter sqlDa = new MySqlDataAdapter(sqlCmd);
sqlDa.Fill(dt);
if (dt.Rows.Count > 0)
{
Response.Write("Succesfully updated");
}
else
{
Response.Write("Error");
}
}
}

Using SQL Between Query and Showing all results in ASP.NET C#

this is my sample code to check the data on Table1 using 2 filters, column1 and between data in column2. The code I have is working but is only getting 1 result. So for example. I enter "1" in textbox1, "3" in textbox2 and "6" in textbox3. Select * from TABLE1 where COLUMN1 = '1' AND COLUMN2 BETWEEN '3' AND '6' -- when run in sql result is 3,4,5,6 but in C# I am only getting "6". Can you help me with this to get "3,4,5,6" as a result. Thank you.
public partial class WebForm1 : System.Web.UI.Page
{
SqlConnection SC;
SqlCommand CMD;
SqlDataReader DR;
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
SC = new SqlConnection(ConfigurationManager.ConnectionStrings["BABBLER"].ConnectionString);
SC.Open();
CMD = new SqlCommand("Select * from TABLE1 WHERE COLUMN1= '" + TextBox1.Text + "' and COLUMN2 Between '" + TextBox2.Text + "'" + " and " + "'" + TextBox3.Text + "'", SC);
DR = CMD.ExecuteReader();
if (DR.HasRows)
{
while (DR.Read())
{
label1.Text = DR["COLUMN2"].ToString();
}
}
}
}
}
Your loop is not appending the values, rather overwriting Label1. Change your while loop to
while (DR.Read())
{
label1.Text += DR["COLUMN2"].ToString() + ",";
}
if (label1.Text.EndsWith(",")) label1.Text = label1.Text.SubString(0, label1.Text.Length-1) //Remove the last comma
Change
label1.Text = DR["COLUMN2"].ToString();
as
label1.Text = label1.Text +", " + DR["COLUMN2"].ToString();
if (Label1.Text.Length > 2)
Label1.Text = Label1.Text.Substring(2);
try this code
SC = new SqlConnection(ConfigurationManager.ConnectionStrings["BABBLER"].ConnectionString);
SC.Open();
CMD = new SqlCommand("Select * from TABLE1 WHERE COLUMN1= '" + TextBox1.Text + "' and COLUMN2 Between '" + TextBox2.Text + "'" + " and " + "'" + TextBox3.Text + "'", SC);
DataSet ds = new DataSet();
SqlDataAdapter da = new SqlDataAdapter(CMD);
da.Fill(ds);
string data="";
for (int i = 0; i < ds.Tables[0].Rows.Count; i++ )
{
if(data=="")
{
label1.Text = ds.Tables[0].Rows[i]["COLUMN2"].ToString();
}
else
{
label1.Text +=","+ ds.Tables[0].Rows[i]["COLUMN2"].ToString();
}
}
There are a number of methods to combine results into a comma-separated list. However, using string concatenation should not be one - concatenating strings is slow, especially if you might have a large number of results. Try one of the following instead:
Using a StringBuilder
StringBuilder sb = new StringBuilder();
boolean doneFirstRow = false;
while (DR.READ())
{
if (doneFirstRow)
{
sb.Append(", ");
}
else
{
doneFirstRow = true;
}
sb.Append(dr["COLUMN2"].ToString());
}
Label1.Text = sb.ToString();
Using a List with String.Join:
List<string> values = new List<string>();
while (DR.READ())
{
values.Add(dr["COLUMN2"].ToString());
}
Label1.Text = String.Join(", ", values);
NB: If not using NET4.5 you'll need String.Join(", ", values.ToArray())

import xml to mdb

I'm trying to export a SQL-Server query to an XML file now and I want to import that file to Access. I don't understand how to do this.
Here is the code I use to generate the XML:
protected void Button1_Click(object sender, EventArgs e) {
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["SqlSconn"].ConnectionString);
con.Open();
string strSQL = "select * from dbo.table_"+test.Text.ToString()+"";
SqlDataAdapter dt = new SqlDataAdapter(strSQL, con);
DataSet ds = new DataSet();
dt.Fill(ds, "" + test.Text.ToString() + "");
ds.WriteXml(Server.MapPath("temp.xml"));
}
This may be a start.
static void SaveToMDB(DataSet ds, string strMDBFile)
{
OleDbConnection cAccess = new OleDbConnection(
"Provider=Microsoft.Jet.OLEDB.4.0;Data source=" + strMDBFile);
cAccess.Open();
foreach (DataTable oTable in ds.Tables)
{
OleDbCommand oCommand = new OleDbCommand(
"DROP TABLE [" + oTable.TableName + "]", cAccess);
try
{
oCommand.ExecuteNonQuery();
}
catch (Exception) { }
string strCreateColumns = "";
string strColumnList = "";
string strQuestionList = "";
foreach (DataColumn oColumn in oTable.Columns)
{
strCreateColumns += "[" + oColumn.ColumnName + "] VarChar(255), ";
strColumnList += "[" + oColumn.ColumnName + "],";
strQuestionList += "?,";
}
strCreateColumns = strCreateColumns.Remove(strCreateColumns.Length - 2);
strColumnList = strColumnList.Remove(strColumnList.Length - 1);
strQuestionList = strQuestionList.Remove(strQuestionList.Length - 1);
oCommand = new OleDbCommand("CREATE TABLE [" + oTable.TableName
+ "] (" + strCreateColumns + ")", cAccess);
oCommand.ExecuteNonQuery();
OleDbDataAdapter da = new OleDbDataAdapter(
"SELECT * FROM [" + oTable.TableName + "]", cAccess);
da.MissingSchemaAction = MissingSchemaAction.Add;
da.FillLoadOption = LoadOption.OverwriteChanges;
da.InsertCommand = new OleDbCommand(
"INSERT INTO [" + oTable.TableName + "] (" + strColumnList
+ ") VALUES (" + strQuestionList + ")", cAccess);
foreach (DataColumn oColumn in oTable.Columns)
{
da.InsertCommand.Parameters.Add(
oColumn.ColumnName,
OleDbType.VarChar,
255,
oColumn.ColumnName
);
}
foreach (DataRow oRow in oTable.Rows)
oRow.SetAdded();
da.Update(oTable);
}
}
This Data will work only with ID and Name, using the system :
using System;using System.Collections.Generic;using System.Linq;using System.Web;using System.Web.UI;using System.Web.UI.WebControls;using System.Data.Sql;using System.Data.SqlClient;using System.Configuration;using System.Data;using System.IO;
using System.Xml.Linq;
//import SelectiveDatabaseBackup.xml to test9 table
string connectionString = ConfigurationManager.ConnectionStrings["ApplicationServices3"].ConnectionString;
SqlConnection sqlConnection1 = new SqlConnection(connectionString);
SqlCommand cmd = new SqlCommand();
cmd.CommandType = CommandType.Text;
DataSet ds = new DataSet();
ds.ReadXml(XDocument.Load("c:/d/SelectiveDatabaseBackup.xml").CreateReader());
foreach (DataTable table in ds.Tables)
{
//Create table
foreach (DataRow row in table.Rows)
{
string name = row[1].ToString();
string id = row[0].ToString();
cmd.CommandText = "INSERT test9 VALUES ('"+ id +"','"+ name + "')";
cmd.Connection = sqlConnection1;
sqlConnection1.Open();
cmd.ExecuteNonQuery();
sqlConnection1.Close();
}
}
//--------------------------

Categories

Resources