Databind a dropdownlist - c#

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

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 get data from SQL and write it in textbox?

I need a help.
I searched and I tried a lot but I am too bad to make it work on my project by myself.
This is code for button-Seek. I want to make Seek-button to fill textbox by respective data.
private void SeekClick(object sender, EventArgs e)
{
if (TBCusNumber.Text != "")
{
string Number = TBCusNumber.Text;
var Conn = new SqlConnection();
Conn.ConnectionString = ConfigurationManager.ConnectionStrings["WindowsFormsApp1.Properties.Settings.DataBase"].ConnectionString;
var Cmd = new SqlCommand();
Cmd.Connection = Conn;
Cmd.CommandText = "SELECT * FROM CustomerList WHERE CustomerNumber = " + Number;
var DataAdapter = new SqlDataAdapter(Cmd);
DataSet DataSet = new DataSet();
DataAdapter.Fill(DataSet, "CustomerList");
CusView.DataSource = DataSet;
CusView.DataMember = "CustomerList";
}
}
And This is the data table.
This is what happens when I put 3 in the text box and press Seek-button.
So here, I want all text boxes to be filled by the data which I searched.
You will get only one row for the query right?
So give like that,
txtFirstName.Text = DataSet.Tables[0].Rows[0]["FirstName"].ToString();
txtLasttName.Text = DataSet.Tables[0].Rows[0]["LastName"].ToString();
Like this you need to assign the values to the respective text boxes.
There are three problem need to fix.
You forget to open the connection with DB,add Conn.Open(); before you excute sql command.
You need to add parameter to prevention SQL Injection
Please use using it will help you to use external resources to return the memory.
when the DataSet be filled you can get the data then fill in textbox
You can follow like this.
private void SeekClick(object sender, EventArgs e)
{
if (TBCusNumber.Text != "")
{
string Number = TBCusNumber.Text;
using (var Conn = new SqlConnection())
{
Conn.ConnectionString = ConfigurationManager.ConnectionStrings["WindowsFormsApp1.Properties.Settings.DataBase"].ConnectionString;
using (var Cmd = new SqlCommand())
{
Cmd.Connection = Conn;
Cmd.CommandText = "SELECT * FROM CustomerList WHERE CustomerNumber = #Number";
Cmd.Parameters.AddWithValue("#Number", Number);
//You miss to add Conn.Open()
Conn.Open();
using (var DataAdapter = new SqlDataAdapter(Cmd))
{
DataSet DataSet = new DataSet();
DataAdapter.Fill(DataSet, "CustomerList");
CusView.DataSource = DataSet;
CusView.DataMember = "CustomerList";
//when the DataSet be filled you can get the data then fill in textbox
txt_firstName.Text = DataSet.Tables[0].Rows[0]["FirstName"].ToString();
}
}
}
}
}

How to get the data when I select a datagridview cell or column

I have 2 datagridview controls in a Windows Forms application.
I would like to get the info of a person when I select first datagridview cell or row to next datagridview:
try
{
ConnectionStringSettings consettings = ConfigurationManager.ConnectionStrings["attendancemanagement"];
string connectionString = consettings.ConnectionString;
SqlConnection con = new SqlConnection(connectionString);
con.Open();
adap3 = new SqlDataAdapter(#"SELECT Date,Attendance,Remarks FROM dailyattendance where employee_id='"+DailyGV.CurrentRow+"'", con);
ds3 = new DataSet();
adap3.Fill(ds3, "dailyattendance");
dataGridView1.DataSource = ds3.Tables[0];
}
Im trying the above code. But it's not working.
I'm not too sure what DailyGV.CurrentRow is but basically you can use the RowHeaderMouseClick...see MSDN documentation. To use it, hook an event handler to it when initializing the form components (you can use VS designer as well...
dataGridView1.RowHeaderMouseClick += dataGridView1_RowHeaderMouseClick;
void dataGridView1_RowHeaderMouseClick(
object sender, DataGridViewCellMouseEventArgs e)
{
}
this event handler will get fired everytime you select a row header in the DataGridView control which will pass information about the event through an instance of the DataGridViewCellMouseEventArgs class (see MSDN documentation). This argument has a RowIndex property that provides the index of the row clicked which you can use to retrieve the values of the cells in that row...including the person id (if provided)...for example...
void dataGridView1_RowHeaderMouseClick(
object sender, DataGridViewCellMouseEventArgs e)
{
string personId = dataGridView1.Rows[e.RowIndex].Cells["PersonId"].Value;
//TODO: implement your own query to retrieve data for that person id
}
notice that you need to provide a proper column name when access the cells collection indexer...Cells["columnName"]
I will not give any description about the solution because Leo and Arsalan Bhatti has already suggested the solution. I am just telling you how your code should looks like and how it should be written.
string connectionString = consettings.ConnectionString;
using (SqlConnection con = new SqlConnection(connectionString))
{
try
{
con.Open();
string empID = DailyGV.CurrentRow.Cells["employee_id"].Value.ToString();
SqlCommand Cmd = con.CreateCommand();
Cmd.CommandText = "SELECT Date,Attendance,Remarks FROM dailyattendance where employee_id=#employee_id";
Cmd.Parameters.Add("#employee_id", SqlDbType.Int).Value = Int32.Parse(empID);
adap3 = new SqlDataAdapter(Cmd);
DataTable dt = new DataTable();
adap3.Fill(dt);
dataGridView1.DataSource = dt;
con.Close();
}
catch
{}
}
try
{
cn.Open();
string query = "select employee_id,Employee_Name,Image_of_Employee from Employee_Details where employee_id='" + dataGridView1.SelectedCells[0].Value.ToString() + "'";
SqlCommand cmd = new SqlCommand(query, cn);
SqlDataReader sdr;
sdr = cmd.ExecuteReader();
if (sdr.Read())
{
string aa = (string)sdr["employee_id"];
string bb = (string)sdr["employee_name"];
txtEmployeeID.Text = aa.ToString();
txtnameofemployee.Text = bb.ToString();
byte[] img=(byte[])sdr["Image_of_employee"];
MemoryStream ms=new MemoryStream(img);
ms.Seek(0,SeekOrigin.Begin);
pictureBox1.Image=Image.FromStream(ms); cn.Close();
}
}
catch (Exception e1)
{
MessageBox.Show(e1.Message);
}
You are passing the current row's index as employee id in SELECT query. Pass employee id for the selected record. Then it will work fine.

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

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