any alternative to xmldatasource in asp.net menu control - c#

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

Related

How to copy Access table to SQL table in C#?

As title says I've used odbcconnection to sqlconnection and for the life of me cant get it to work.. Copied a bunch of code from this site but cant get them both to work.
The program just hangs so maybe I am doing something wrong, but would appreciate maybe a bare bones template that i could just fill in the connection details and bulk copy the table to table..
using (OdbcConnection myConnection = new OdbcConnection())
{
string myConnectionString = #"Driver={Microsoft Access Driver (*.mdb)};" +
"Dbq=//####/data/Toronto/wrkgrp/wrkgrp30/Business Risk Oversight and Control/DATA INTEGRITY/CDE/CDE Testing Portal Requirements/Migration Requirements/RCM/Mutual Funds/Mutual Funds.mdb;";
myConnection.ConnectionString = myConnectionString;
myConnection.Open();
//execute queries, etc
OdbcCommand cmd = myConnection.CreateCommand();
cmd.CommandText = "SELECT * FROM RCM_MF_New_Accounts_Samples";
OdbcDataReader reader = cmd.ExecuteReader(); // close conn after complete
DataTable myDataTable = new DataTable();
myDataTable.Load(reader);
//myConnection.Close();
string destinationConnectionString = "Data Source=####;Initial Catalog=DYOF_STAGING_BROC;User ID=;Password=;Connection Timeout=999";
SqlConnection destination = new SqlConnection(destinationConnectionString);
SqlBulkCopy bulkData;
//destination.Open();
Exception ex = null;
try
{
Console.WriteLine("step1");
bulkData = new SqlBulkCopy(destinationConnectionString, SqlBulkCopyOptions.FireTriggers);
bulkData.BulkCopyTimeout = 1;
bulkData.DestinationTableName = "Load_CTR_Sample_Account_Opening2";
bulkData.WriteToServer(myDataTable);
bulkData.Close();
Console.WriteLine("moved from here to there");
reader.Close();
//destination.Close();
}
catch (Exception e)
{
ex = e;
}
I actually wrote an ORM to make this kind of task easier.
var accessDS = new AccessDataSource(connectionString1);
var dt = accessDS.From("RCM_MF_New_Accounts_Samples").ToDataTable().Execute();
var sqlDS = new SqlServerDataSource(connectionString2);
sqlDS.InsertBulk("Load_CTR_Sample_Account_Opening2", dt).Execute();
This does not work for .NET Core.
Packages:
https://www.nuget.org/packages/Tortuga.Chain.Access/
https://www.nuget.org/packages/Tortuga.Chain.SqlServer
Read the data from Access into a DataTable:
string strConnect = #"Provider=Microsoft.ACE.OLEDB.12.0;data source=D:\Temp\MyDB.accdb";
DataTable dt = new DataTable();
using (OleDbConnection con = new OleDbConnection(strConnect))
{
OleDbCommand cmd = new OleDbCommand("SELECT * FROM MyTable", con);
con.Open();
OleDbDataAdapter da = new OleDbDataAdapter(cmd);
da.Fill(dt);
}
Then use SqlBulkCopy to update SQL:
string strConnect = #"Data Source=GRIFFPC\SQLEXPRESS;Initial Catalog=Testing;Integrated Security=True";
using (SqlConnection con = new SqlConnection(strConnect))
{
con.Open();
using (SqlBulkCopy bulk = new SqlBulkCopy(con))
{
bulk.DestinationTableName = "Test";
bulk.WriteToServer(dt);
}
}
Of course, there is a much easier way to go straight from Access to SQL Server, using VBA, SQL , or other methods.
https://support.office.com/en-us/article/import-or-link-to-data-in-an-sql-server-database-a5a3b4eb-57b9-45a0-b732-77bc6089b84e
https://www.sqlshack.com/six-different-methods-to-copy-tables-between-databases-in-sql-server/
Here's a basic example of bulk insert.
public void BulkInsert(DataTable employees)
{
if (employees == null)
throw new ArgumentNullException(nameof(employees), $"{nameof(employees)} is null.");
using (var con = OpenConnection())
using (var sbc = new SqlBulkCopy(con))
{
sbc.DestinationTableName = "HR.Employee";
foreach (DataColumn column in employees.Columns)
sbc.ColumnMappings.Add(column!.ColumnName, column.ColumnName);
sbc.WriteToServer(employees);
}
}
Note the foreach (DataColumn column in employees.Columns) loop. This is required so that it knows the column names are the same in the source and the target table. (If they're not the same, manually map them in the same fashion.)
Source: https://grauenwolf.github.io/DotNet-ORM-Cookbook/BulkInsert.htm#ado.net
Following option need to verify
1) Column Name should be the same.
2) verify the column length.
3) verify the data type.

How to select a value from Dropdownlist and pass value to Gridview?

I am having trouble with my SQL statement to pass the value from my dropdownlist select to my gridview. I tested my SQL statement Serve Management Studio, with a specific date, and it works, but it isn't working with select value from my Dropdownlist. How would I pass the value to the Gridview? Thank you for help, I am new student to the asp.net world.
Image of web application:
Image of My DATABASE:
public void RefreshDay()
{
SqlConnection conn = new SqlConnection(#"data source =.\sqlexpress; integrated security = true; database = DBdentist");
SqlDataAdapter da = null;
DataSet ds = null;
DataTable dt = null;
string sqlsel = "SELECT Distinct patient.patientID, day from patient, patientreservation where patient.patientID = patientreservation.patientID";
try
{
da = new SqlDataAdapter();
da.SelectCommand = new SqlCommand(sqlsel, conn);
ds = new DataSet();
da.Fill(ds, "myDay");
dt = ds.Tables["myDay"];
DropDownListDay.DataSource = dt;
DropDownListDay.DataTextField = "day";
DropDownListDay.DataValueField = "patientID";
DropDownListDay.DataBind();
DropDownListDay.Items.Insert(0, "Select Day");
}
catch (Exception ex)
{
LabelDay.Text = ex.Message;
}
finally
{
conn.Close();
}
}
protected void DropDownListDay_SelectedIndexChanged(object sender, EventArgs e)
{
if (DropDownListDay.SelectedIndex != 0)
{
SqlConnection conn = new SqlConnection(#"data source =.\sqlexpress; integrated security = true; database = DbDentist");
SqlDataAdapter da = null;
DataSet ds = null;
DataTable dt = null;
string sqlsel = "SELECT patientreservation.patientID, patient.firstname, patient.lastname, patientreservation.day, patientreservation.hour, treatment.treatment FROM((patientreservation INNER JOIN patient ON patientreservation.patientID = patient.patientID) INNER JOIN treatment ON patientreservation.treatmentID = treatment.treatmentID) WHERE patientreservation.day = " + DropDownListDay.SelectedValue + "";
try
{
da = new SqlDataAdapter();
da.SelectCommand = new SqlCommand(sqlsel, conn);
ds = new DataSet();
da.Fill(ds, "myDay");
dt = ds.Tables["myDay"];
GridViewDay.DataSource = dt;
GridViewDay.DataBind();
}
catch (Exception ex)
{
LabelDay.Text = ex.Message;
}
finally
{
conn.Close();
}
}
else
{
LabelDay.Text = "You choose None:";
}
}
}
}
You can simply use this:
WHERE patientreservation.day = '" + DropDownListDay.Text.ToString() + "'";
Thanks for the help. I tried everything
DropDownListDay.DataTextField = "day";
DropDownListDay.DataValueField = "day"
helped. I was also having some problem with my gridview. I added up deleting it and making a new, somehow that help.
The configuration of your dropdown is
DropDownListDay.DataTextField = "day";
DropDownListDay.DataValueField = "patientID";
but you need the day as a value if you want to filter with the current selected value
DropDownListDay.DataTextField = "day";
DropDownListDay.DataValueField = "day";
SELECT patientreservation.patientID, patient.firstname, patient.lastname, patientreservation.day, patientreservation.hour, treatment.treatment FROM((patientreservation INNER JOIN patient ON patientreservation.patientID = patient.patientID) INNER JOIN treatment ON patientreservation.treatmentID = treatment.treatmentID) WHERE **patientreservation.day** = " + DropDownListDay.**SelectedValue** + "";
Or you can try with WHERE **patientreservation.day** = " + DropDownListDay.**SelectedText** + "";
The dropdownlist is not triggering the event. Try to put this AutoPostBack="true" in your asp dropdownlist tag.

How to get data from DB, store as List<>, and display the results to view

I am trying to get data as a list from the database but it is not showing any results. I tried to debug but after this line it doesn't let me to step over / F10:
DataSet ds = new DataSet();
da.Fill(ds);
I am trying to do this by following this example on here: link 1 and here link 2 but finding it difficult hence I thought that I should ask here.
Can someone please explain why it is not displaying the results and as such what I may be doing wrong here? how do I work around and achieve it to display the data?
Here's the full controller code for your inspection:
public static List<DBTrack> GetListOfTracks()
{
if (DBTrackData == null)
{
string myConnectionString = "Data Source="; // I have taken off the source
string mySelectString = "SELECT TrackID, AddedDate, TrackName, ArtistName from TBL_Track";
SqlDataAdapter da = new SqlDataAdapter();
DataSet ds = new DataSet();
da.Fill(ds);
OleDbConnection myConnection = new OleDbConnection(myConnectionString);
OleDbCommand myCommand = new OleDbCommand(mySelectString, myConnection);
myCommand.Connection.Open();
OleDbDataReader myReader = myCommand.ExecuteReader(CommandBehavior.CloseConnection);
List<DBTrack> list = new List<DBTrack>();
while (myReader.Read())
{
DBTrack data = new DBTrack();
data.TrackID = (Guid)(myReader["TrackID"]);
data.AddedDate = (DateTime)myReader["AddedDate"];
data.TrackName = (string)myReader["TrackName"];
data.ArtistName = (string)myReader["ArtistName"];
list.Add(data);
};
}
return DBTrackData;
}
EDIT:
SqlConnection mySQLconnection = new SqlConnection(#"Data Source=server-2\SQLExpress;Initial Catalog=End;Integrated Security=False;User ID=test1;Password=**");
SqlCommand mySelectString = new SqlCommand("SELECT TrackID, AddedDate, TrackName, ArtistName from TBL_Track");
using (SqlConnection connection = new SqlConnection("context connection=true"))
{
connection.Open();
using (SqlCommand myCommand = new SqlCommand // The best overload method System.Data.SqlClient.SqlCommand.SqlCommand has some invalid arguments
(mySelectString, mySQLconnection)) // Cannot convert from System.Data.SqlClient.SqlCommand to 'string'
{
You should set the DBTrackData to the result of the list:
while (myReader.Read())
{
...
}
DBTrackData = list;
You could also directly edit the DBTrackData in your code:
private static List<DBTrack> DBTrackData
public static List<DBTrack> GetListOfTracks()
{
if (DBTrackData == null)
{
...
DBTrackData = new List<DBTrack>();
while (myReader.Read())
{
DBTrack data = new DBTrack();
...
DBTrackData.Add(data);
};
}
return DBTrackData;
}
So, in full it should be:
public static List<DBTrack> GetListOfTracks()
{
try
{
if (DBTrackData == null)
{
string myConnectionString = "Data Source="; // I have taken off the source
string mySelectString = "SELECT TrackID, AddedDate, TrackName, ArtistName from TBL_Track";
using (OleDbConnection myConnection = new OleDbConnection(myConnectionString))
{
myConnection.Open();
using (OleDbCommand myCommand = new OleDbCommand(mySelectString, myConnection))
{
OleDbDataReader myReader = myCommand.ExecuteReader(CommandBehavior.CloseConnection);
List<DBTrack> list = new List<DBTrack>();
while (myReader.Read())
{
DBTrack data = new DBTrack();
data.TrackID = (Guid)(myReader["TrackID"]);
data.AddedDate = (DateTime)myReader["AddedDate"];
data.TrackName = (string)myReader["TrackName"];
data.ArtistName = (string)myReader["ArtistName"];
list.Add(data);
}
DBTrackData = list;
}
}
}
return DBTrackData;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
return DBTrackData;
}
Your main problem is that you are using two different ways of getting the data, but the first is only partially implemented. You are using a data adapter and a data reader. Your data adapter isn't even being passed a connection or query, so this is why it is not working. So you can just remove that part of the code.
It's also easier to read if you immediately return when DBTrackData is not null rather than have a big if block over the whole code. You will then have something like:
public static List<DBTrack> GetListOfTracks()
{
if (DBTrackData != null) return DBTrackData;
string myConnectionString = "Data Source="; // I have taken off the source
string mySelectString = "SELECT TrackID, AddedDate, TrackName, ArtistName from TBL_Track";
OleDbConnection myConnection = new OleDbConnection(myConnectionString);
OleDbCommand myCommand = new OleDbCommand(mySelectString, myConnection);
myCommand.Connection.Open();
OleDbDataReader myReader = myCommand.ExecuteReader(CommandBehavior.CloseConnection);
List<DBTrack> list = new List<DBTrack>();
while (myReader.Read())
{
DBTrack data = new DBTrack();
data.TrackID = (Guid)(myReader["TrackID"]);
data.AddedDate = (DateTime)myReader["AddedDate"];
data.TrackName = (string)myReader["TrackName"];
data.ArtistName = (string)myReader["ArtistName"];
list.Add(data);
};
//Setting DBTrackData means these values will get returned on every call to GetListOfTracks for this instance of the class
DBTrackData = list;
return list;
}

Databind a dropdownlist

When I try to databing dropdownlist, got this: system.data.datarowview
what do I wrong?
string strQuery = "Select Item FROM Calendar Where UserD="Test";
SqlConnection myConn;
SqlDataAdapter sqlDa = new SqlDataAdapter(strQuery,myConn);
DataTable sqlTa = new DataTable("Test");
da.Fill(sqlTa);
ddlList.DataSource = sqlTa;
ddlList.DataBind();
string strQuery = "Select Item FROM Calendar Where UserD='Test'";
Note you need to use single quotations around the string, as in your code you didn't finish the inital string ever, so the rest of the code just became part of strQuery.
In addition if you bring back more than one field in the future, when you bind a dropdown list you need to specify which field from the database is the value and which is the displayed text.
ddlList.DataSource = sqlTa;
ddlList.DataValueField = "ValueFieldFromDatabaseResults";
ddlList.DataTextField = "ShownTextFieldFromDatabaseResults";
ddlList.DataBind();
You need to tell it what fields to use as value and text.
ddlList.DataSource = sqlTa;
ddlList.DataValueField = "ValueField";
ddlList.DataTextField = "TextField";
ddlList.DataBind();
And your select statement is missing a ". It should be:
"Select Item FROM Calendar Where UserD='Test'"
An Example being:
As ryan pointed out if you are pulling back one field then you can just do:
DataTable dtTable = new DataTable();
try
{
using (SqlConnection sqlConnection = new SqlConnection("Your connection"))
{
using (SqlCommand sqlCommand = new SqlCommand("Select Item FROM Calendar Where UserD='Test'", sqlConnection))
{
sqlConnection.Open();
using (SqlDataReader sqlDataReader = sqlCommand.ExecuteReader())
{
dtTable.Load(sqlDataReader);
sqlDataReader.Close();
}
}
}
}
catch (Exception error)
{
throw error;
}
ddlList.DataSource = dtTable;
ddlList.DataBind();
But if you have more then one field then you can do this:
DataTable dtTable = new DataTable();
try
{
using (SqlConnection sqlConnection = new SqlConnection("Your connection"))
{
using (SqlCommand sqlCommand = new SqlCommand("Select Item, id FROM Calendar Where UserD='Test'", sqlConnection))
{
sqlConnection.Open();
using (SqlDataReader sqlDataReader = sqlCommand.ExecuteReader())
{
dtTable.Load(sqlDataReader);
sqlDataReader.Close();
}
}
}
}
catch (Exception error)
{
throw error;
}
ddlList.DataSource = dtTable;
ddlList.DataValueField = "id";
ddlList.DataTextField = "item";
ddlList.DataBind();
add this line way
ddlList.DataSource = sqlTa;
ddlList.DataValueField = "ValueFieldFromDatabaseResults";
ddlList.DataTextField = "ShownTextFieldFromDatabaseResults";
ddlList.DataBind();
then u miss connection string for
SqlConnection myConn="must add your connection string code here "
You have not open connection string so
add myconn.open()
for
SqlConnection myConn="must add your connection string code here "
`myconn.open()`
SqlDataAdapter sqlDa = new SqlDataAdapter(strQuery,myConn)
Try this..
ddlList.DataSource = sqlTa;
ddlList.DataTextField = "class";
ddlList.DataBind();
adding ddList.Value="somefield" is optional

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