Create DataTable from SQL Connection String in Web.config file - c#

I need to display data from a table in my SQL Server DB on a webpage. I've got a connection string in my Web.config file like this:
<connectionStrings>
<add name="Products.ConnectionString"
connectionString="Data Source=...."
providerName="System.Data.SqlClient" />
</connectionStrings>
<system.web>
<compilation debug="true" targetFramework="4.5" />
<httpRuntime targetFramework="4.5" />
</system.web>
In my aspx I've got a GridView with a ObjectDataSource to display the data.
In the code behind I created a method in terms of a List to return the values from my database table. However, now I was told that the users need to be able to filter the data so I created a textbox and a button to enable this but then realised in this case it would be better to have a DataTable than a List. I've always used Lists for those kind of projects though so I'm not sure how to achieve the same in a DataTable.
Here is what the code for my List looks like:
public class Products
{
public string Name { get; set;}
public int Price { get; set; }
public List<Products> DataTable()
{
List<Products> myList = new List<Products>();
string sqlQuery = "SELECT * FROM [Products_Table] ";
string connectionString = ConfigurationManager.ConnectionStrings["Products_ConnectionString"].ConnectionString; //Read connection string from config file
using (var con = new SqlConnection(connectionString))
{
using (var cmd = new SqlCommand(sqlQuery, con))
{
con.Open(); //Open connection
using (var reader = cmd.ExecuteReader())
{
while (reader.Read())
{
Products t = new Products();
t.Name = reader["Name"].ToString();
t.Price = Convert.ToInt32(reader["Price"]);
myList.Add(t);
}
}
}
}
return myList;
}
}
So would be great if somebody could get me on the right track for replacing the list with a DataTable in the first place.

In your code behind you need to do something like this:
public static class ProductsDataSource
{
public static DataTable LoadProducts()
{
using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["Products_ConnectionString"].ConnectionString))
using (SqlCommand command = new SqlCommand("SELECT * FROM Products_Table", conn))
{
DataTable data = new DataTable();
SqlDataAdapter adapter = new SqlDataAdapter(command);
adapter.Fill(data);
return data;
}
}
}
Since you're using ObjectData Source make sure you're defining the SelectMethod and Typename correctly in order to return the data. Something like this:
<asp:ObjectDataSource ID="ObjectDataSource1" runat="server"
TypeName="ProductsDataSource"
SelectMethod="LoadProducts"
/>

Something like -
GridView1.DataSource = DataTable();

SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["dbcs"].ConnectionString);
string SQL = "SELECT * FROM [Table];";
SqlDataAdapter adapter = new SqlDataAdapter(SQL, conn);
DataTable dt = new DataTable();
adapter.Fill(dt);
GridView1.DataSource = dt;
GridView1.DataBind();
I dont know of that`s what you are looking for, but this is how you bind a GridView with a DataTable.

Related

creating a list which works as inparameter for gridview

I'm working on a school development project and I'm quite new to development. I have been reading online but can't find the answer I'm looking for.
So far I have created a listbox in my Windows Forms application which I want to select all the values from one of my columns, and these should work as a inparameter to display data in my dataGridView based on the parameter.
I have created 70% of my project and this functionality is what is left. My database is in Azure and I can write to it and add new rows, but I can't read anything to my application when I run it.
code for listview, at first I just want to be able to select. Later on somehow write the choosen parameter to a variable that I can use as a condition in my dataGridView.
This is the code for my gridview so far I just want to display all data in it, but it's not showing anything.
namespace MyNamespace
{
public partial class CompanyForm : Form
{
public CompanyForm()
{
InitializeComponent();
}
//Connection String
string cs = ConfigurationManager.ConnectionStrings["ConnectionString"].
ConnectionString;
private void createCompany_Click_1(object sender, EventArgs e)
{
if (textBoxCompanyName.Text == "")
{
MessageBox.Show("Fill information");
return;
}
using (SqlConnection con = new SqlConnection(cs))
{
//Create SqlConnection
con.Open();
SqlCommand cmd = new SqlCommand
(
"insert into dbo.Company (companyName)
values(#companyName)", con);
cmd.Parameters.AddWithValue
(
"#companyName",
textBoxCompanyName.Text);
SqlDataAdapter adapt = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
adapt.Fill(ds);
MessageBox.Show("GJ");
}
}
// The code that is not filling my datagrid
private void dataEmployees_Load()
{
using (SqlConnection con = new SqlConnection(cs))
{
con.Open();
SqlCommand cmd = new SqlCommand
(
"Select fname,ename FROM dbo.Users", con
);
SqlDataReader dr = cmd.ExecuteReader();
DataTable dt = new DataTable();
dt.Load(dr);
dataEmployees.DataSource = dt;
}
}
}
}
My connection string is working it's already being able to insert data to the tables that I have.
The problem why you Grid isn't shown any data is that you try to bind a SqlDataReader to it. This isn't working, because the Grid doesn't support this as DataSource.
What you need as DataSource is DataTable, IList<T>, IBindingList<T>. In your case the DataTable would be the easiest solution. Try this out:
protected void DataEmployees()
{
using (SqlConnection con = new SqlConnection(cs))
{
con.Open();
SqlCommand cmd = new SqlCommand
(
"Select firstname,lastname FROM employees",con
);
SqlDataReader dr = cmd.ExecuteReader();
DataTable dt = new DataTable();
dt.Load(dr);
dataEmployees.DataSource = dt;
}
}
Notice that Methods are written Uppercase in C#. Further notice that you don't need to close the connection manually if you use a using-block. On the end of the using-block it's automatically closed/disposed.

C# - Datagridview does not show data from MySQL

I have a datagridview which should contain all users in mysql database. For my problem, it adds rows based on the number of rows in the MySQL, but does not show any data on it. see image below (i have 2 rows in database):
screenshot
Here's my code that I've tried:
using MySql.Data.MySqlClient;
namespace SampleDatabaseQueries
{
public partial class Main : Form
{
public Main()
{
InitializeComponent();
}
MySqlConnection conn;
MySqlCommand cmd;
private void Main_Load(object sender, EventArgs e)
{
string connString = "server=localhost;user=root;password=;database=test_db";
conn = new MySqlConnection(connString);
showData();
}
public void showData()
{
string query = "SELECT * FROM test_db.users;";
cmd = new MySqlCommand(query, conn);
conn.Open();
MySqlDataAdapter adapter = new MySqlDataAdapter();
adapter.SelectCommand = cmd;
DataTable dTable = new DataTable();
adapter.Fill(dTable);
dgUsers.DataSource = dTable;
conn.Close();
}
}
}
EDIT: above code works, data was already loaded but it adds another column so I did not see at first (as you can see the long horizontal scroll on the above screenshot). To solve that, I removed the columns I manually added and changed my query to:
SELECT username AS Username, password AS Password FROM test_db.users;
Thank you!
Replace this:
MySqlDataAdapter adapter = new MySqlDataAdapter();
With:
using (MySqlDataAdapter reader = new MySqlDataAdapter(cmd))
{
adapter.Fill(dTable);
}
EDIT
For further improvement you could make a database connection class, i suppose you are using the MySql connector from oracle so you can check out their documentation on how to do this. Here is a link that can get you started on the most basic things like connecting and filling datatables: MySql connector documentation
EDIT 1
As you said my solution did not work, here is another one that I just tested and should work.
DataTable dTable = new DataTable();
conn.Open();
string query = "SELECT * FROM test_db.users;";
MysqlCommand cmd = new MySqlCommand(query, conn);
using (MySqlDataAdapter reader = new MySqlDataAdapter(cmd))
{
adapter.Fill(dTable);
}
dgUsers.DataSource = dTable;
conn.Close();
This should work. If the datatable is not showing any rows(Empty rows means it found something), then there is a different problem, maybe your database is empty.

Change tables loaded in the grid with dropdownlist

I am doing this for my own learning. It is not home work. All example I have found are for asp solutions.
I have a Grid and a DropDownList in a Winform.
The Grid has a DataSet a BindingSource and a TableAdapter.
I populate the dropdownlist with the tables in the DB as following:
public void FillDropDownList(string connString)
{
String Query = "SELECT * FROM information_schema.tables where Table_Name like 'Table%'";
using (var cn = new SqlConnection(connString))
{
cn.Open();
DataTable dt = new DataTable();
try
{
SqlCommand cmd = new SqlCommand(Query, cn);
SqlDataReader myReader = cmd.ExecuteReader();
dt.Load(myReader);
}
catch (SqlException e)
{
//to be completed
}
radDropDownList1.DataSource = dt;
radDropDownList1.ValueMember = "TABLE_NAME";
radDropDownList1.DisplayMember = "TABLE_NAME";
}
}
The line that loads the data in the grid is like this:
this.table_xxxTableAdapter.Fill(this.xxxDataSet.Table_xxx);
So I suspect that with these components I would need a new dataset for each table but I do not like to do that because new tables may be created in the future.
How can I change the table loaded in the grid selecting tables from the dropdownlist?
A DataSet requires that you specify the tables you may want to load at design time, but it sounds like you want to load these tables dynamically (because they may get added to the database from another source?)
If I'm understanding your question correctly, you should simply do this:
Whenever the user selects a table, load the selected table using a dynamic query and re-databind the grid to it. The code should look something like this. Note: This is untested code.
protected void radDropDownList_OnSelectedIndexChanged(object sender, EventArgs e)
{
DataTable dt = new DataTable();
string query = BuildQuery(radDropDownList.SelectedValue); //Pass in the table name
using (var cn = new SqlConnection(connString))
{
cn.Open();
try
{
SqlCommand cmd = new SqlCommand(query, cn);
using (var da = new SqlDataAdapter(cmd))
{
ad.Fill(dt);
}
}
catch (SqlException e)
{
//TODO: Handle this exception.
}
}
radGrid.DataSource = dt;
radGrid.DataBind();
}
private string BuildQuery(string table)
{
//TODO: Provide your own implementation for your query.
return string.Format(
#"SELECT * FROM {0}", table);
}

Solve the error "The ConnectionString property has not been initialized."?

My code is view all the data in the gridview
Web.config code is
<configuration>
<connectionStrings>
<add name="ConStr" connectionString="DataSource=.;Integrated Security=SSPI;Initial catalog=sshopping"/>
</connectionStrings>
<system.web>
<compilation debug="true" targetFramework="4.5"/>
<httpRuntime targetFramework="4.5"/>
</system.web>
</configuration>
It is coded in external class
namespace DBAction
{
public class ViewAction
{
public DataSet GetAllData()
{
SqlCommand cmd = DataConnection.GetConnection().CreateCommand();
cmd.CommandText = "Select UserName,Password,RoleName,EmailID,SecurityQuestion,SecurityAnswer,LastLogin from LoginInfo";
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
cmd.Dispose();
DataConnection.CloseConnection();
return ds;
}
}
}
it is giving error in line da.Fill(ds)
The code to bind data source with gridview is coded on page load like this.
DataSet ds = new ViewAction().GetAllData();
gvLoginInfo.DataSource = ds;
gvLoginInfo.DataBind();
And conectionstring code in data connection class is
public static SqlConnection GetConnection()
{
if (con == null)
{
con = new SqlConnection();
con.ConnectionString = ConfigurationManager.ConnectionStrings["ConStr"].ConnectionString;
con.Open();
}
return con;
}
And one one error is
Exception Details: System.ArgumentException: Keyword not supported: 'datasource'.
Source Error:
Line 19: {
Line 20: con = new SqlConnection();
Line 21: con.ConnectionString =ConfigurationManager.ConnectionStrings["ConStr"].ConnectionString;
Line 22: con.Open();
Line 23: }
The error is in the Web.Config only. Please put one space between DataSource in connectionString as: Data Source. Thus your connection String will become:
"Data Source=.;Integrated Security=SSPI;Initial catalog=sshopping".
From the examples i see online, in your connection string replace "DataSource" with "Data Source" (with a space between the two words).
http://msdn.microsoft.com/en-us/library/ms156450.aspx
I was getting same error, even after made all changes you mentioned above.
And after that, I change my code in that way:
My Web.Config:
<connectionStrings>
<add name="conStr" connectionString="Data Source=SomeDS;Initial Catalog=SomeCatalog;User Id=myId;Password=myPass" />
</connectionStrings>
My old Code:
string ConnectionString = ConfigurationManager.ConnectionStrings["conStr"].ConnectionString;
using (var sqlConnection = new SqlConnection(ConnectionString ))
{
var result= sqlConnection.Query<My_Class>("MY_PROC_NAME", new { count }, commandType: CommandType.StoredProcedure);
return result;
}
My newCode:
var dt = new DataTable();
using (var cnn = new SqlConnection(ConnectionString ))
using (var cmd = new SqlCommand("MY_PROC_NAME", cnn))
{
cmd.CommandType = CommandType.StoredProcedure;
cnn.Open();
var sqlReader = cmd.ExecuteReader();
if (sqlReader.HasRows)
dt.Load(sqlReader);
cnn.Close();
}
result = dt.DataTableToList<My_Class>();
DataTableToList is a converter method, if you need i can share it, too.

Loading combobox from database in C#

I am creating an application, where I can add a customer's first name, last name, email, the date, service type (pc repair), the technician PC brand, pc type, type of OS, and the problem with the computer. I am able to insert data into the MySQL database using phpMyAdmin.
However, I a stuck on this part. I am trying to view the service order that was just created. I would like to load the combobox by the last name of the customer, and once I click on the customer's name, it populates all the fields that were mentioned above and the service number that it was inserted into the database. I am having issues loading the combobox and texfields.
Any ideas are appreciated! If a combobox is a bad idea and there is a better way, please let me know! I tried this code, but SQLDataAdapter is not working for me. I somehow can't find an example that I can relate too.
private void cbViewServices_SelectedIndexChanged(object sender, EventArgs e)
{
if (cbViewServices.SelectedIndex >- 1)
{
string lastName = cbViewServices.SelectedValue.ToString();
MySqlConnection conn = new MySqlConnection("server=localhost;uid=******;password=**********;database=dboserviceinfo;");
conn.Open();
SqlDataAdapter da = new SqlDataAdapter("select distinct LastName from tserviceinfo where LastName='" + lastName + "'", conn);
DataSet ds = new DataSet();
da.Fill(ds); conn.Close();
}
}
I do not recommend using the 'Lastname' as a parameter to load your details since that field most likely isn't unique. Unless that is the case in your program.
This sample does the following:
Load customer ID (or lastname in your case) to a combobox.
Handle the combobox's change event and pass it as a parameter to a
method that will use that to load the details.
Load the customer details using the passed parameter.
A couple of guidelines:
Enclose disposable objects in a 'using' statement so it will be
disposed properly.
Do not use string concatenation to create your SQL statements. Use
SQL parameters instead, that way you'll avoid SQL injection and make
your code clearer.
Take a look at MySQL .NET connector provider documentation for best practices.
//Load customer ID to a combobox
private void LoadCustomersId()
{
var connectionString = "connection string goes here";
using (var connection = new MySqlConnection(connectionString))
{
connection.Open();
var query = "SELECT Id FROM Customers";
using (var command = new MySqlCommand(query, connection))
{
using (var reader = command.ExecuteReader())
{
//Iterate through the rows and add it to the combobox's items
while (reader.Read())
{
CustomerIdComboBox.Items.Add(reader.GetString("Id"));
}
}
}
}
}
//Load customer details using the ID
private void LoadCustomerDetailsById(int id)
{
var connectionString = "connection string goes here";
using (var connection = new MySqlConnection(connectionString))
{
connection.Open();
var query = "SELECT Id, Firstname, Lastname FROM Customer WHERE Id = #customerId";
using (var command = new MySqlCommand(query, connection))
{
//Always use SQL parameters to avoid SQL injection and it automatically escapes characters
command.Parameters.AddWithValue("#customerId", id);
using (var reader = command.ExecuteReader())
{
//No customer found by supplied ID
if (!reader.HasRows)
return;
CustomerIdTextBox.Text = reader.GetInt32("Id").ToString();
FirstnameTextBox.Text = reader.GetString("Firstname");
LastnameTextBox.Text = reader.GetString("Lastname");
}
}
}
}
//Pass the selected ID in the combobox to the customer details loader method
private void CustomerIdComboBox_SelectedIndexChanged(object s, EventArgs e)
{
var customerId = Convert.ToInt32(CustomerIdComboBox.Text);
LoadCustomerDetailsById(customerId);
}
I'm not entirely sure if this is what your looking for but most of the guidelines still applies.
Hope this helps!
Try something like this to bind data to the combo box:
public void ListCat()
{
DataTable linkcat = new DataTable("linkcat");
using (SqlConnection sqlConn = new SqlConnection(#"Connection stuff;"))
{
using (SqlDataAdapter da = new SqlDataAdapter("SELECT LastName FROM list WHERE LastName <> 'NULL'", sqlConn))
{
da.Fill(linkcat);
}
}
foreach (DataRow da in linkcat.Rows)
{
comboBox1.Items.Add(da[0].ToString());
}
}
Taken from my own question.
SqlDataAdapter is used to communicate with SQL Server rather than MySQL.
Try the following:
MySqlDataAdapter da = new MySqlDataAdapter("select distinct LastName from tserviceinfo where LastName='" + lastName + "'", conn);
We can also use while loop. When completing the database connection after the SQLDatareader we can use while loop.
"userRead " is SQLData reader
while (userRead.Read())
{
cboxReportNo.Items.Add(userRead[1].ToString());
}
bind your dataset in ComboBox DataSource
this.comboBox1.DataSource = ds;
this.comboBox1.DisplayMember = "LastName";
this.comboBox1.ValueMember = "Id";
this.comboBox1.SelectedIndex = -1;
this.comboBox1.AutoCompleteMode = AutoCompleteMode.Append;
this.comboBox1.AutoCompleteSource = AutoCompleteSource.ListItems;
//USING
using System;
using System.Drawing;
using System.Windows.Forms;
using System.Data.SqlClient;
using System.Data;
namespace YourNamespace
{
//Initialization
string connetionString = null;
SqlConnection cnn;
SqlCommand cmdDataBase;
SqlDataReader reader;
DataTable dt;
public frmName()
{
//
// The InitializeComponent() call is required for Windows Forms designer support.
//
InitializeComponent();
//
// TODO: Add constructor code after the InitializeComponent() call.
//
FillComboNameOfCombo();
}
void FillcmbNameOfCombo()
{
string sqlQuery = "SELECT * FROM DATABASENAME.[dbo].[TABLENAME];";
connetionString = "Data Source=YourPathToServer;Initial Catalog=DATABASE_NAME;User ID=id;Password=pass";
cnn = new SqlConnection(connetionString);
cmdDataBase = new SqlCommand(sqlQuery, cnn);
try {
cnn.Open();
reader = cmdDataBase.ExecuteReader();
dt = new DataTable();
dt.Columns.Add("ID", typeof(string));
dt.Columns.Add("COLUMN_NAME", typeof(string));
dt.Load(reader);
cnn.Close();
cmbGender.DataSource = dt;
cmbGender.ValueMember = "ID";
cmbGender.DisplayMember = "COLUMN_NAME";
dt = null;
cnn = null;
cmdDataBase = null;
connetionString = null;
reader = null;
}
catch (Exception ex) {
MessageBox.Show("Can not open connection ! " + ex.ToString());
}
}
}

Categories

Resources