I'm trying to figure out how to pull specific Entry lines from an Access Database and into a C# Program.
I'm working with a friend to make a sudoku game. We want to pull different levels of difficulty of puzzles from an access database and into a C# program.
Now my question is: Is there a way to have to program pull the specific lines from the database or would we need to load them all into the program and then have them selected from there? These would be put into a two-dimensional array.
What would be the best way to go about this?
I'm not sure what soduku is, but I'm thinking that you need to query your Access DB. Something like this should get you started.
Class BusLogic
{
public List<string> ListboxItems = new List<string>();
public void PopulateListBoxItems(string userName)
{
string connString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\redgabanan\Desktop\Gabanan_Red_dbaseCon\Red_Database.accdb";
using (OleDbConnection connection = new OleDbConnection(connString))
{
connection.Open();
OleDbDataReader reader = null;
OleDbCommand command = new OleDbCommand("SELECT * from Users WHERE LastName='#1'", connection);
command.Parameters.AddWithValue("#1", userName)
reader = command.ExecuteReader();
while (reader.Read())
{
ListboxItems.Add(reader[1].ToString()+","+reader[2].ToString());
}
}
}
}
You could use a DataReader as well.
http://www.akadia.com/services/dotnet_data_reader.html
You definitely don't want to pull in all data from a Table; you need to somehow Query the data set.
Related
I am a beginner at C# and .NET oop concepts. I want to load the datagridview. I don't know how to pass the data. What I tried so far I attached below.
I created a class std
public void get()
{
SqlConnection con = new SqlConnection("server =.; initial catalog=testdb; User ID=sa; Password=123");
string sql = "select * from std";
con.Open();
SqlCommand cm = new SqlCommand(sql, con);
SqlDataReader dr = cm.ExecuteReader();
while ( dr.Read())
{
string stname = dr["st_name"].ToString();
string nicnum = dr["nic"].ToString();
}
con.Close();
}
Form: I am getting data like this way
std ss = new std();
ss.get();
dataGridView1.Rows.Clear();
If I wrote like this way how to pass data into the datagridview columns? I am stuck in this area
It's easier like this:
public void FillGrid()
{
var dt = new DataTable();
var da = new SqlDataAdapter("select * from std", "server =.; initial catalog=testdb; User ID=sa; Password=123");
da.Fill(dt);
dataGridView1.DataSource = dt;
}
but if you're going to use such a low level method of database access you should consider adding a DataSet type of file to your project; visual studio will write all this code and more for you with a few mouse clicks, and it makes a good job of creating tables and adapters that are a lot easier to work with
you have made multiple mistakes. First you read data wirh dataraeader and in every iteration define two stname and nimnum variables like. So when loop ends variables are destroyed. You have to define data table and read data by dataraeader and and add them to it row by row. Or read by sqldataadapter and read it immediately and pass to datatable object.Finnaly you pass datatable as return object of function. Use this vala as datasource of datagridview property if I'm not wrong.
I've got the code below to populate a datagrid in a C# WPF application. I've been told that I should "Close" the connection as soon as I have retrieved the data I need. However once the connection has been closed so does the reader and I lose the itemsource for my datagrid. How would I maintain the contents of this datagrid once I close the connection and reader? To clarify, once the data has been retrieved the datagrid contents won't change.
Code:
OleDbConnection conn = new OleDbConnection { ConnectionString = DataBase.ConnectionString() };
conn.Open();
OleDbDataReader reader = null;
OleDbCommand command = new OleDbCommand("SELECT [ID],[ClassName] FROM Class WHERE TeacherID = #TeacherID", conn);
command.Parameters.AddWithValue("#TeacherID", Properties.Settings.Default.UserID);
reader = command.ExecuteReader();
_ClassGrid.ItemsSource = reader; //_ClassGrid is my DataGrid
conn.Close();
The code will function fine, if I remove the conn.close();
Thanks for any help in advance, it's much appreciated.
So when you are displaying data, you need to "bind" or set your item source to a disconnected object, and not the data source directly. You should also ensure that you dispose of all disposable objects in your code. If you do not have a lot of data, the simplest thing to do would be use fill a datatable. If you do have a lot of data, then you should use POCO's in a collection. The following code shows for a datatable:
DataTable stuffToDisplay = new DataTable();
using (var conn = new OleDbConnection { ConnectionString = DataBase.ConnectionString() })
{
conn.Open();
using(var command = new OleDbCommand("SELECT [ID],[ClassName] FROM Class WHERE TeacherID = #TeacherID", conn))
{
command.Parameters.AddWithValue("#TeacherID", Properties.Settings.Default.UserID);
using(var adapter = new OleDbDataAdapter(command))
{
adapter.Fill(stuffToDisplay);
}
}
}
// Looks like you need to set to default view in WPF
_ClassGrid.ItemsSource = stuffToDisplay.DefaultView;
That is kind of a rough cut, so take that with a grain of debugging salt. But give something like that a shot. Here is a link to the data adapter class on MSDN, it should give you some idea of how to use it.
https://msdn.microsoft.com/en-us/library/system.data.oledb.oledbdataadapter(v=vs.110).aspx
If you do have a lot of data, then you should consider using objects instead of a data table (I think that is more excepted anyways). I would do some reading on binding and observable collections to get your WPF right for that situation, using a data reader to fill objects (or entity framework). Here are some related questions to that, which would be faster than me posting a ton of code on it.
WPF - Binding to collection in object
Bind collection of objects to ListBox
https://social.msdn.microsoft.com/Forums/vstudio/en-US/1f211699-5764-47ae-9ad9-d9ff2875e9c0/how-to-set-listboxitemssource-to-a-collection-of-objects-in-xaml?forum=wpf
https://msdn.microsoft.com/en-us/library/system.windows.controls.itemscontrol.itemssource%28v=vs.110%29.aspx?f=255&MSPPError=-2147217396
Im trying to populate a text box with infromation that is searched by using a customerID which is inputted throught a text box here is the code im using below
private void txtCustomerID_TextChanged(object sender, EventArgs e)
{
string strCon = Properties.Settings.Default.PID2dbConnectionString;
OleDbConnection conn = new OleDbConnection(strCon);
String sqlPoints = "SELECT points FROM customer WHERE [customerID]=" + txtCustomerID.Text;
txtPoints.Text = sqlPoints;
}
but the text box "txtPoints" only outputs the text of the sqlpoints and not the information in the database? I'm not exactly sure what im doing wrong here.
Any help is appreciated, thanks in advance.
You are not executing the SQL statement on the database. Instead, you are assigning it to txtPoints.Text. You need to execute it on the DB server using, e.g., an OleDbCommand object.
What you need to do instead is something like the following (note this is pseudo-code - I haven't tested it runs)
using (OleDbConnection conn = new OleDbConnection(strCon))
{
String sqlPoints = "SELECT points FROM customer WHERE [customerID]=" + txtCustomerID.Text;
// Create a command to use to call the database.
OleDbCommand command = new OleDbCommand(sqlPoints, conn)
// Create a reader containing your results
using(OleDbReader reader = command.ExecuteReader())
{
reader.Read(); // Advance to the first row.
txtPoints.Text = reader[0].ToString(); // Read the contents of the first column
}
}
Note also my use of using. This will ensure that your database connections are properly closed once you are finished with them.
All I want to do is a very simple select/picklist with values from a MySQL database.
I'm trying to find a simple solution online (I'm new to C#) and everything I'm finding is very complicated.
All I want to do is generate the <select><option.. etc parts, with all the attributes and values that I want to set.
This seems like it should be very, very easy. Can anyone give me some basic instructions, or point me to a tutorial that shows how to accomplish this?
Currently, I am using MySqlCommand and MySqlDataReader for classes to talk to the database (for another function).
Create a class for the entity you want to display. Ex : If you want to show all states in the dropdown, create State class
public class State
{
public int ID { set;get;}
public string Name { set;get;}
}
Now write a method in which you query the database and get the result to the DataReader, Iterate over the items and set the values a new object of our State class. Add each object to a list (of State class). So your method's return type will be a List of State class object.
public List<State> GetStates()
{
List<State> stateList=new List<State>();
// execute query, read from reader and add to the stateList
// the below code is SqlServer DB specific.
// you need to change the Connection,Command class for it to use with MySql.
using (var con= new SqlConnection("replace your connection string"))
{
string qry="SELECT ID,NAME FROM STATES";
var cmd= new SqlCommand(qry, objConnection);
cmd.CommandType = CommandType.Text;
con.Open();
using (var objReader = cmd.ExecuteReader())
{
if (objReader.HasRows)
{
while (objReader.Read())
{
var item=new State();
item.ID=reader.GetInt32(reader.GetOrdinal("ID"));
item.Name=reader.GetString(reader.GetOrdinal("Name"));
stateList.Add(item);
}
}
}
}
return stateList;
}
Now, have a DropDownList control in your page,
<asp:DropDownList id="states" runat="server" />
Now in the codebehind of this page, you can set the data for the dropdown( possibly in the Page_Load event)
if(!isPostBack)
{
states.DataSource=yourRepositary.GetStates();
states.DataTextField="Name";
states.DataValueField="ID";
states.DataBind();
}
I think what you searching for is something like a DropDownList, it accepts a DataSource, so you can use your already populated MySqlDataReader as it.
Something like this
MySqlDataReader dr = //the code to fill the MySqlDataReader
DropDownList1.DataSource = dr;
You can create the DropDownList in the design of your page.
To show the data you need to set then the values
DropDownList1.DataValueField = "DbField1";
DropDownList1.DataTextField = "DbField2";
Generally, in a list/drop down you got (a) the value that will be selected and (b) its presentation to the user. The first one might be some primary key, the second might be some label which is self-explaining to the user.
Assuming you got a table FOOD like
FoodValue | FoodLabel
---------------
00010 | Sausage
00020 | Eggs
00030 | Cheese
Put a listbox in your ASP.NET view, e.g. listBox1, then
you can read it in the code behind using
MySqlConnection con = new MySqlConnection("YOUR CONNECTION STRING");
MySqlCommand cmd = new MySqlCommand("SELECT FoodValue, FoodLabel FROM FOOD", con);
con.Open();
MySqlDataReader r = cmd.ExecuteReader();
while(r.Read()) {
listBox1.Items.Add(new ListItem(r["FoodLabel"], r["FoodValue"]);
}
con.Close();
But keep in mind this is a quick and dirty approach. In production code, you will need some separation of the presentation and data layer. Use the data source controls to bind your data in a better way.
I am trying to get column information in C# from a SQL table on SQL Server. I am following the example in this link: http://support.microsoft.com/kb/310107 My program strangely gets hung up when it tries to close the connection. If the connection is not closed, the program exits without any Exceptions. Here's my code:
SqlConnection connection = new SqlConnection(#"MyConnectionString");
connection.Open();
SqlCommand command = new SqlCommand("SELECT * FROM MyTable", connection);
SqlDataReader reader = command.ExecuteReader(CommandBehavior.KeyInfo); // If this is changed to CommandBehavior.SchemaOnly, the program runs fast.
DataTable table = reader.GetSchemaTable();
Console.WriteLine(table.Rows.Count);
connection.Close(); // Alternatively If this line is commented out, the program runs fast.
Putting the SqlConnection inside a using block also causes the application to hang unless CommandBehavior.KeyInfo is changed to CommandBehavior.SchemaOnly.
using (SqlConnection connection = new SqlConnection(#"MyConnectionString"))
{
connection.Open();
SqlCommand command = new SqlCommand("SELECT * FROM MyTable", connection);
SqlDataReader reader = command.ExecuteReader(CommandBehavior.KeyInfo); // If this is changed to CommandBehavior.SchemaOnly, the program runs fast even here in the using
DataTable table = reader.GetSchemaTable();
Console.WriteLine(table.Rows.Count);
}
The table in question has over 3 million rows, but since I am only obtaining the Schema information, I would think this wouldn't be an issue. My question is: Why does my application get stuck while trying to close a connection?
SOLUTION: Maybe this isn't optimal, but it does work; I inserted a command.Cancel(); statement right before Close is called on connection:
SqlConnection connection = new SqlConnection(#"MyConnectionString");
connection.Open();
SqlCommand command = new SqlCommand("SELECT * FROM MyTable", connection);
SqlDataReader reader = command.ExecuteReader(CommandBehavior.KeyInfo); // If this is changed to CommandBehavior.SchemaOnly, the program runs fast.
DataTable table = reader.GetSchemaTable();
Console.WriteLine(table.Rows.Count);
command.Cancel(); // <-- This is it.
connection.Close(); // Alternatively If this line is commented out, the program runs fast.
I saw something like this, long ago. For me, it was because I did something like:
SqlCommand command = new SqlCommand("SELECT * FROM MyTable", connection);
SqlDataReader reader = command.ExecuteReader();
// here, I started looping, reading one record at a time
// and after reading, say, 100 records, I'd break out of the loop
connection.Close(); // this would hang
The problem is that the command appears to want to complete. That is, go through the entire result set. And my result set had millions of records. It would finish ... eventually.
I solved the problem by adding a call to command.Cancel() before calling connection.Close().
See http://www.informit.com/guides/content.aspx?g=dotnet&seqNum=610 for more information.
It looks right to me overall and I think you need a little optimization. In addition to the above suggestion regarding avoiding DataReader, I will recommend to use connection pooling. You can get the details from here :
http://www.techrepublic.com/article/take-advantage-of-adonet-connection-pooling/6107854
Could you try this?
DataTable dt = new DataTable();
using(SqlConnection conn = new SqlConnection("yourConnectionString"))
{
SqlCommand cmd = new SqlCommand("SET FMTONLY ON; " + yourQueryString + "; SET FMTONLY OFF;",conn);
conn.Open();
dt.Load(cmd.ExecuteReader());
}
SET FMTONLY ON/OFF from MSDN seems the way to go
There is an specific way to do this, using SMO (SQL Server management objects)
You can get the collection of tables in the database, and then read the properties of the table you're interested in (columns, keys, and all imaginable properties)
This is what SSMS uses to get and set properties of all database objects.
Look at this references:
Database.Tables Property
Table class
This is a full example of how to get table properties:
Retrieving SQL Server 2005 Database Info Using SMO: Database Info, Table Info
This will allow you to get all the possible information from the database in a very easy way. there are plenty of samples in VB.NET and C#.
I would try something like this. This ensures all items are cleaned up - and avoids using DataReader. You don't need this unless you have unusually large amounts of data that would cause memory issues.
public void DoWork(string connectionstring)
{
DataTable dt = new DataTable("MyData");
using (var connection = new SqlConnection(connectionstring))
{
connection.Open();
string commandtext = "SELECT * FROM MyTable";
using(var adapter = new SqlDataAdapter(commandtext, connection))
{
adapter.Fill(dt);
}
connection.Close();
}
Console.WriteLine(dt.Rows.Count);
}