C# from db to treeview menu creation - c#

I aim to create treeview menu with using dt ,ds and geting data from DB tables. My code like down below. Got error at Ds I mark it inside code you can see.. it gives an error " Incorrect Systax near 'İşlemleri' " , İşlemleri is part of value that tnParent.Text contains. ( Gişe İşlemleri)
void fill_Tree2()
{
DataSet PrSet = PDataset("select * from mnu_tbl_mnuElmnlr");
treeView1.Nodes.Clear();
foreach (DataRow dr in PrSet.Tables[0].Rows)
{
TreeNode tnParent = new TreeNode();
tnParent.Text = dr["MenuAdi"].ToString(); /////////////////// 'Gişe İşlemleri'
tnParent.Tag = dr["id"].ToString();
tnParent.Expand();
treeView1.Nodes.Add(tnParent);
FillChild(tnParent, tnParent.Text);
}
}
public void FillChild(TreeNode parent, string ParentId)
{
DataSet ds = PDataset("Select altMenuAdi from mnu_tbl_AltElmnlr where ustMenuId = (select id from mnu_tbl_mnuElmnlr));
parent.Nodes.Clear();
foreach (DataRow dr in ds.Tables[0].Rows)
{
TreeNode child = new TreeNode();
child.Text = dr["altMenuAdi"].ToString();
// child.Tag = dr["ChildId"].ToString().Trim();
parent.Nodes.Add(child);
}
}
protected DataSet PDataset(string Select_Statement)
{
SqlConnection conn = new SqlConnection();
// conn.ConnectionString = ConfigurationManager.ConnectionStrings["1123"].ConnectionString;
SqlConnection SqlCon = new SqlConnection("server=123;Database=123;Trusted_Connection=True;");
SqlDataAdapter ad = new SqlDataAdapter(Select_Statement, SqlCon);
DataSet ds = new DataSet();
ad.Fill(ds); /////// Here it gives an error " Incorrect Systax near 'İşlemleri' "
return ds;
}

Related

How to get excel rows one by one in command text using loop?oledb,c#

I am using oledb to read excel file and then i am trying to apply some conditions and then save in db, but i just want to read excel row one by one using loop.
var cmd = conn.CreateCommand();
cmd.CommandText = "select * from [الحيازات$]";// want to get this rows using loop so
//that only specific row is selected perform opertion blow then i will save in db,but
//its selecting all rows now
using (var rdr = cmd.ExecuteReader())
{
//LINQ query - when executed will create anonymous objects for each row
var query = (from DbDataRecord row in rdr
select row)
.Select(x =>
{
//dynamic item = new ExpandoObject();
Dictionary<string, string> item = new Dictionary<string, string>();
for (int i = 0; i < x.FieldCount; i++)
{
//code
}
});
}
Please check this
private void ReadExcel()
{
try
{
string connectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + filePath + #";Extended Properties=""Excel 12.0;HDR=YES;IMEX=1;""";
using (OleDbConnection connection = new OleDbConnection())
{
connection.ConnectionString = connectionString;
using (OleDbCommand command = connection.CreateCommand())
{
command.CommandText = "SELECT * FROM [Sheet1$]";
connection.Open();
OleDbDataAdapter dataAdapter = new OleDbDataAdapter(command);
DataSet dataSet = new DataSet();
dataAdapter.Fill(dataSet);
if (dataSet != null && dataSet.Tables[0] != null)
{
foreach (DataRow row in dataSet.Tables[0].Rows)
{
string value = row["EmailColumnName"].ToString();
}
}
}
}
}
catch (Exception ex)
{
//Handle Exception
}
}

Getting value from last row of SQL Server database C#

public queue getQueueDataByID(int queueID)
{
string DBConnect = ConfigurationManager.ConnectionStrings["ConnStr"].ConnectionString;
SqlDataAdapter da;
DataSet ds = new DataSet();
queue myQueue = new queue();
StringBuilder sqlCommand = new StringBuilder();
sqlCommand.AppendLine("Select * from QueueTable where");
sqlCommand.AppendLine("id = #paraId");
try
{
SqlConnection myConn = new SqlConnection(DBConnect);
// sqlCommand.Parameters.AddWithValue("paraCustId", tbCustId.Text);
da = new SqlDataAdapter(sqlCommand.ToString(), myConn);
da.SelectCommand.Parameters.AddWithValue("paraId", queueID);
// fill dataset
da.Fill(ds, "QueueTable");
//conn.Close();
int rec_cnt = ds.Tables["QueueTable"].Rows.Count;
DataRow row = ds.Tables["QueueTable"].Rows[rec_cnt-1 ];
myQueue.queueNo = row["QueueNo"].ToString();
myQueue.NRIC = row["NRIC"].ToString();
myQueue.ContactNo = row["ContactNo"].ToString();
}
catch (SqlException ex)
{
}
return myQueue;
}
This is my class,I am trying to retrieve the datas from the last row of the database to display in a web form, any idea how i can do that? My "id", primary key is set as autoincrement.
You can use Linq on the datatable to get the last row.
var queueDataTable = ds.Tables[0];
var lastDataRow = queueDataTable.AsEnumerable().Last();
If you need to itterate through all the rows in the datatable
foreach (var dataRow in queueDataTable.AsEnumerable())
{
}
thanks

Update sql database using dataset

I need some help to complete this. I have searched and tried several ways but is not enetring in my head yet. It is not homework! I am a self learner.
I managed to populate a grid selecting the table from a dropdown:
private void radDropDownList1_SelectedIndexChanged(object sender, Telerik.WinControls.UI.Data.PositionChangedEventArgs e)
{
if (radDropDownList1.SelectedIndex > 0)
{
radGridView1.Visible = true;
label8.Text = radDropDownList1.SelectedValue.ToString();
DataTable dt = new DataTable();
var selectedTable = radDropDownList1.SelectedValue; //Pass in the table name
string query = #"SELECT * FROM " + selectedTable;
using (var cn = new SqlConnection(connString))
{
cn.Open();
try
{
SqlCommand cmd = new SqlCommand(query, cn);
using (var da = new SqlDataAdapter(cmd))
{
da.Fill(dt);
}
}
catch (SqlException ex)
{
//MessageBox.Show(ex.StackTrace);
}
}
radGridView1.DataSource = dt;
}
Now I am trying to write the event to update the sql table using the grid as datasource:
private void radGridView1_CellEndEdit(object sender, Telerik.WinControls.UI.GridViewCellEventArgs e)
{
DataTable dt = (DataTable)radGridView1.DataSource;
DataSet ds = new DataSet();
ds.Tables[0] = dt;
try
{
//**I am lost here!**
}
catch
{
}
}
Could you please help? How can I now update the sql table?
I don't really like the way you are managing the updates but... this code here will send an update statement:
using (var cn = new SqlConnection(connString))
{
cn.Open();
try
{
SqlCommand cmd = new SqlCommand("UPDATE YourTable SET Column = #Parm1 WHERE Col = #Parm2", cn);
var parm1 = cmd.CreateParameter("Parm1");
parm1.Value = "SomeValue";
var parm2 = cmd.CreateParameter("Parm2");
parm2.Value = "SomeOtherValue";
cmd.Parameters.Add(parm1);
cmd.Parameters.Add(parm2);
int rowsAffected = cmd.ExecuteNonQuery();
}
catch (SqlException ex)
{
//MessageBox.Show(ex.StackTrace);
}
}

Simple Database Comparison

I am trying to compare two databases from different dates. I want to load my 'Orders' table from the ending database into a DataTable, then convert that DataTable to a Dictionary<string,int> where string = OrderNumber and int = ClientNumber.
Once I have the Dictionary into memory, I will run my function that goes out to the beginning database and performs a atrOrdersEND.ContainsKey(ordernumber) check. If it is exists nothing will be done, if it does not exist, I want the information of the DataRow to be saved somewhere.
Is this the best way to go about this?
If not, how should I?
static public DataTable getDatabaseInfo(string DB)
{
DB = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + DB;
OleDbConnection conn = new OleDbConnection(DB);
string query = "SELECT * FROM ORDERS;";
OleDbCommand cmd = new OleDbCommand(query, conn);
OleDbDataAdapter da = new OleDbDataAdapter(cmd);
DataTable dt = new DataTable();
conn.Open();
try
{
da.Fill(dt);
}
catch (OleDbException ex)
{
}
return dt;
}
static Dictionary<string,int> ToDictionary(DataTable DT)
{ //this doesn't work, I get the 'An item with the same key has already been added' error
var Dict = (from order in DT.AsEnumerable()
select new
{
OrderNumber = order.Field<string>("OrderNumber"),
ClientNumber = order.Field<int>("Client")
}).AsEnumerable()
.ToDictionary(k => k.OrderNumber, v => v.ClientNumber);
return Dict;
}
static public void CheckHistoryBEG(string DB)
{
DB = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + DB;
OleDbConnection conn = new OleDbConnection(DB);
string query = "SELECT * " +
"FROM Orders";
OleDbDataAdapter adapter = new OleDbDataAdapter(query, conn);
DataTable dt = new DataTable();
try
{
adapter.Fill(dt);
for (int i = 0; i <= dt.Rows.Count - 1; i++)
{
string ordernumber = dt.Rows[i]["OrderNumber"].ToString();
if (atrOrdersEND.ContainsKey(ordernumber))
{
atrOrdersEND[ordernumber] = atrOrdersEND[ordernumber] + 1;
}
else
{
atrOrdersEND.Add(ordernumber, 1);
}
}
}
catch (OleDbException ex)
{
}
}
public Main()
{
DataTable EndDB_Data = getDatabaseInfo(endDBLocation);
Dictionary<string, int> atrOrdersBEG = ToDictionary(EndDBData);
CheckHistoryBEG(beginningDBLocation);
}
You can avoid writing any C# code by using linked tables in your MS Access database. From one DB you can reference the table in the other database. Then you can do joins or existence queries between the two databases.

How do I cast a XElement as string in c#?

Here is my code:
SqlConnection conn4 = new SqlConnection("Data Source=.\\sqlexpress;Initial Catalog=test_BdbCSSQL01;Persist Security Info=False;Integrated Security=SSPI;");
conn4.Open();
string sql = "SELECT * FROM ERROROfSIDESStagingOUT";
SqlDataAdapter da = new SqlDataAdapter(sql, conn4);
DataTable dt = new DataTable();
da.Fill(dt);
DataRow dr;
dr = dt.NewRow();
dt.Rows.Add(dr);
XDocument doc = XDocument.Load("XmlString.xml");
XNamespace ns = "https://uidataexchange.org/schemas";
var node = doc.Descendants(ns + "EmployerTPASeparationResponse");
var node2 = node.ElementAt(i);
foreach (var param in node2.Elements())
{
try
{
if (dr[param.Name.LocalName].ToString() == "PriorIncidentOccurrence")
{
var PriorIncidentDescendants = param.Descendants(ns + "PriorIncidentOccurrence");
dr["PriorIncidentID"] = PriorIncidentDescendants.ElementAt(0).Value;
}
if (dr.Table.Columns.Contains(param.Name.LocalName))
{
dr[param.Name.LocalName] = param.Value;
}
}
catch (Exception ee)
{
//TODO: SendMail
string asdf = ee.ToString();
}
}
SqlCommandBuilder sb = new SqlCommandBuilder(da);
da.Update(dt);
if (conn4 != null)
{
conn4.Close();
}
I am trying to cast dr[param.Name.LocalName] as type string. Both of the following do not work.
(string)dr[param.Name.LocalName]
dr[param.Name.LocalName].ToString()
It is my guess, that you are calling dr[param.Name.LocalName] before you have assigned a value to that key in your first if statement.
You should probably state the error you recieve. I'm guessing it has nothing to do with casting...
You could try to check the value of param.Name.LocalName in the debugger (or print it with Debug.WriteLine) and make sure that the values are all valid column names in your DataRow.

Categories