How do I cast a XElement as string in c#? - 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.

Related

How to sort a dataset in ASP.NET C#

I am trying to sort a datatable into a DataSet. I want to sort by the Status Column in "DESC". But I am not aware how to go about this. I have tried the suggested solutions online but I seem not to be doing something right. Here is what I have tried, albeit, I have commented out the sorting lines of the code as they do not work for me. How can I sort my table using the Status column in Desc?
[WebMethod(EnableSession = true)]
public List < TaskListClass > getTasks() {
var userId = Session["UserId"].ToString();
List < TaskListClass > objB = new List < TaskListClass > ();
try {
using(var connection = new SqlConnection(ConfigurationManager.ConnectionStrings["DBConnString"].ToString())) {
connection.Open();
DataSet Myds = new DataSet();
// Myds.Tables[0].DefaultView.Sort = "Status desc";
SqlDataAdapter sqldr = new SqlDataAdapter();
string ProcName = "getTasks";
SqlCommand cmd = new SqlCommand(ProcName, connection);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("#userId", SqlDbType.VarChar, 900).Value = userId;
sqldr.SelectCommand = cmd;
sqldr.Fill(Myds);
DataTable dt = Myds.Tables[0];
// DataTable dt = Myds.Tables[0].DefaultView.ToTable();
for (int i = 0; i < dt.Rows.Count; i++) {
objB.Add(new TaskListClass() {
Id = Convert.ToString(dt.Rows[i]["Id"]),
Subject = Convert.ToString(dt.Rows[i]["Subject"]),
Customer = Convert.ToString(dt.Rows[i]["Customer"]),
Sender = Convert.ToString(dt.Rows[i]["Sender"]),
Receiver = Convert.ToString(dt.Rows[i]["Receiver"]),
Priority = Convert.ToString(dt.Rows[i]["Priority"]),
StartDate = Convert.ToString(dt.Rows[i]["StartDate"]),
EndDate = Convert.ToString(dt.Rows[i]["EndDate"]),
Status = Convert.ToString(dt.Rows[i]["Status"]),
OnProgress = Convert.ToString(dt.Rows[i]["OnProgress"]),
});
}
}
} catch (Exception e) {
msg = e.ToString();
}
return objB;
}
Ok, a few things.
first up, a dataset is a collection of tables - "many tables" possible.
But you have ONE table, so why use a dataset? I see no need. Just use a single data table for this.
And this will reduce the code.
So, I suggest this, or close to this:
using (var connection = new SqlConnection(ConfigurationManager.ConnectionStrings["DBConnString"].ToString()))
{
using (var cmd = new SqlCommand("getTasks", connection))
{
connection.Open();
cmd.CommandType = CommandType.StoredProcedure;
DataTable dt = new DataTable();
cmd.Parameters.Add("#userId", SqlDbType.VarChar).Value = userId;
dt.Load(cmd.ExecuteReader());
// now sort the datatable
dt.DefaultView.Sort = "Status DESC";
// now fill out our object with each row
foreach (DataRow OneRow in dt.Rows)
{
objB.Add(new TaskListClass()
{
Id = OneRow["Id"].ToString(),
Subject = OneRow["Subject"].ToString(),
Customer = OneRow["Customer"].ToString(),
Sender = OneRow["Sender"].ToString(),
Receiver = OneRow["Receiver"].ToString(),
Priority = OneRow["Priority"].ToString(),
StartDate = OneRow["StartDate"].ToString(),
EndDate = OneRow["EndDate"].ToString(),
Status = OneRow["Status"].ToString(),
OnProgress = OneRow["OnProgress"].ToString(),
}); ;
}
}
}
}
return objB;
The way the current code is written, you could add this after the for-loop:
objB = objB.OrderByDescending(t => t.Status).ToList();
Depending of the datatype of Status, it might be sorted alphabetically.
var dataRow = dt.AsEnumerable().OrderByDescending(x => x.Field<string>("Status")).ToList();
foreach (var item in dataRow)
{
//Enter your Code Here
}
Here dt is your datatable.
dataRow is a set of list.
After get the data list, you can asign it to your "objB".

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
}
}

Get the Row values from a excel based on the column Value

I am trying to a get the Row values from a excel sheet, based on the column Value.
e.g. I have CutsomerID as lets say 5 , so I want First name 5, last Name 5 and Address 5
I am converting whole excel sheet into DataTable and then trying to read on each DataRow, when I get CustomerID as 5, I copy all the values and break from the loop
Here is my code and it is working fine as well, but I was wondering is there any way to optimise it.
Here is my Code.
public ExcelData GetDataByCustomerID(String excelFilePath, String customerID)
{
OleDbConnectionStringBuilder connectionStringBuilder = new OleDbConnectionStringBuilder();
connectionStringBuilder.Provider = "Microsoft.ACE.OLEDB.12.0";
connectionStringBuilder.DataSource = excelFilePath;
connectionStringBuilder.Add("Mode", "Read");
const string extendedProperties = "Excel 12.0;IMEX=1;HDR=YES";
connectionStringBuilder.Add("Extended Properties", extendedProperties);
String connectionString = connectionStringBuilder.ToString();
// Create connection object by using the preceding connection string.
using( var objConn = new OleDbConnection(connectionString))
{
objConn.Open();
// Get the data table contaning the schema guid.
DataTable excelSheetsDataTable = objConn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
if (excelSheetsDataTable == null)
return null;
// get all the tables in the Sheet
List<String> excelSheets = (from DataRow row in excelSheetsDataTable.Rows select row["TABLE_NAME"].ToString()).ToList();
// Our data is on First sheet only
OleDbCommand _oleCmdSelect = new OleDbCommand(#"SELECT * FROM [" + excelSheets[0] + "]", objConn);
OleDbDataAdapter oleAdapter = new OleDbDataAdapter();
oleAdapter.SelectCommand = _oleCmdSelect;
DataTable newDataTable = new DataTable();
oleAdapter.FillSchema(newDataTable, SchemaType.Source);
oleAdapter.Fill(newDataTable);
if (newDataTable.Columns.Contains("CustomerID"))
{
foreach (DataRow rowValue in newTB.Rows)
{
if ((string) rowValue["CustomerID"] == customerID)
{
var data = new ExcelData
{
customerFirstName = rowValue["Customer_First_ Name"].ToString(),
customerLastName = rowValue["Customer_Last_Name"].ToString(),
customerAddress = rowValue["Customer_Address"].ToString(),
};
return data;
}
}
String message = String.Format("The CustomerID {0} not found in Excel file {1}", customerID, excelFilePath);
MessageBox.Show(message);
}
else
{
String message = String.Format("The Column CustomerID not found in Excel file {0}", excelFilePath);
MessageBox.Show(message);
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
return null;
}
public class ExcelData
{
public String customerID;
public String customerFirstName;
public String customerLastName;
public String customerAddress;
}
Change your select query to like below -
#"SELECT * FROM [" + excelSheets[0] + "] WHERE CustomerID=<your_value>"
Courtesy msdn web site:
Link: MSDN
DataTable dt;
private void button1_Click(object sender, EventArgs e)
{
try
{
openFileDialog1.ShowDialog();
string connectionString = string.Format("Provider = Microsoft.Jet.OLEDB.4.0;Data Source ={0};Extended Properties = Excel 8.0;", this.openFileDialog1.FileName);
var con = new OleDbConnection(connectionString);
var cmd = new OleDbCommand("select * from [sheet1$] where [MRN#]=#c", con);
cmd.Parameters.Add("#c", "33264");
con.Open();
var dr = cmd.ExecuteReader();
if (dr.HasRows)
{
dt = new DataTable();
dt.Load(dr);
}
dr.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
DataGridView dv = new DataGridView();
this.Controls.Add(dv);
dv.DataSource = dt;
}
}
EDIT:
As per your code you should try the below lines of code:
OleDbCommand _oleCmdSelect = new OleDbCommand(#"SELECT * FROM [" + excelSheets[0] + "]" + " Where [CustomerID#] = #custID" , objConn);
_oleCmdSelect.Parameters.Add("#custID", customerID);
OleDbDataAdapter oleAdapter = new OleDbDataAdapter();
oleAdapter.SelectCommand = _oleCmdSelect;

C# from db to treeview menu creation

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;
}

any alternative to xmldatasource in asp.net menu control

my code is as follows
DataSet ds = new DataSet();
string connStr = "Data Source=PARITAS00024;Initial Catalog=MenuDb;Persist Security Info=True;User ID=sa;Password=paritas123";
using (SqlConnection conn = new SqlConnection(connStr))
{
string sql = "Select MenuId, MenuTitle, MenuDesc, MenuURL, ParentMenuId from tblMenus where Status=1 and RecordStatus=1 order by ParentMenuId, DisplayOrder";
SqlDataAdapter da = new SqlDataAdapter(sql, conn);
da.Fill(ds);
da.Dispose();
}
ds.DataSetName = "Menus";
ds.Tables[0].TableName = "Menu";
DataRelation relation = new DataRelation("ParentChild", ds.Tables["Menu"].Columns["MenuId"], ds.Tables["Menu"].Columns["ParentMenuId"], true);
relation.Nested = true;
ds.Relations.Add(relation);
System.Web.UI.WebControls.XmlDataSource xds = new System.Web.UI.WebControls.XmlDataSource();
xds.TransformFile = "~/TransformXSLT.xsl";
xds.XPath = "MenuItems/MenuItem";
xds.Data = ds.GetXml();
xds.ID = "xmlDataSourceMenu";
Menu1.DataSource = xds;
Menu1.DataBind();
is this correct way of using the xmldatasource ?
The advantages of using of data sources are related to declarative programming: move the focus from how work must be done to the results. If you are using a datasource in imperative way, you lose all the advantages.
In that code you are giving your menu some XML data got transforming the XML representation of a DataSet returned by a query through an XSL transformation: do you really need to do all that work?
Why don't populate the menu programmatically?
foreach (DataRow parentItem in ds.Tables[0].Rows)
{
MenuItem item = new MenuItem((string)parentItem["Name"]);
menu.Items.Add(categoryItem);
...
}
or, why don't use the XmlDataSource in the aspx:
<asp:XmlDataSource TransformFile="~/TransformXSLT.xsl" XPath="MenuItems/MenuItem" ID="xmlDataSourceMenu" runat="server" />
and, in code behind:
...
xmlDataSourceMenu.Data = ds.GetXml();
...
try
{
XmlDocument xdoc = new XmlDocument();
SqlConnection cnn = null;
SqlCommand cmd = null;
// connection string from web.config
cnn = new SqlConnection(ConfigurationManager.ConnectionStrings["____"].ConnectionString);
cnn.Open();
// SP must return hierarchy of menu items.
string strUSP = "USP_XMLStoredProcedureName";
cmd = new SqlCommand(strUSP, cnn);
XmlReader reader = cmd.ExecuteXmlReader();
if (reader.Read()) { xdoc.Load(reader); }
// DRAG AND DROP XMLDataSource from toolbox , provide id as "DataSourceXML"
DataSourceXML.Data = xdoc.InnerXml.ToString();
// To avoid root
DataSourceXML.XPath = "/ParentMenu/SubMenu";
// :: Provide XMLDatasource ID to Menucontrol.
// OR
XmlDataSource XDS = new XmlDataSource();
XDS.ID = "XMLDataSourceID";
XDS.Data= xdoc.InnerXml;
// To avoid root
XDS.XPath = "/ParentMenu/SubMenu";
MyMenu.DataSource = XDS;
MyMenu.DataBind();
}
catch (Exception ex)
{
throw ex;
}
finally
{
cmd.Dispose();
cnn.Close();
}

Categories