DataGridView not showing my columns - c#

I have a MySQL connection in C# that supposedly puts the table data into a DataGridView, but it has a problem and it makes the rows for every account in my users table in my db, but it doesn't show the actual data. Can anyone help?
My code:
public Form1()
{
InitializeComponent();
string connectionString = "Server=mysql.dunkycart.com; Database=dunkycart; Uid=dunkycart; Pwd=rooB-dnK-sqL;"; //Set your MySQL connection string here.
string query = "SELECT name, username, email FROM users"; // set query to fetch data "Select * from tabelname";
using (MySqlConnection conn = new MySqlConnection(connectionString))
{
using (MySqlDataAdapter adapter = new MySqlDataAdapter(query, conn))
{
DataSet ds = new DataSet();
adapter.Fill(ds);
dataGridView1.DataSource = ds.Tables[0];
}
}
}
The issue:

Nevermind, I just found a fix. What I had to do is set the DataPropertyName for each column in the DataGridView to the corresponding column in the db table.

Because you are using DataSet instead of DataTable so you need to change this:
adapter.Fill(ds);
To this:
adapter.Fill(ds,"tbl");
Or you can use a DataTable instead of DataSet:
DataTable dt = new DataTable();
adapter.Fill(dt);

Related

Getting "This row already belongs to another table & Input array is longer than the number of columns in this table."

if I used finalTable.Rows.Add(row.ItemArray) it gives me this error "Input array is longer than the number of columns in this table."
con.Open();
cmd.Connection = con;
cmd.CommandText = "SELECT CustomerName FROM Customers";
SqlDataAdapter adp = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
adp.Fill(ds);
DataTable finalTable = new DataTable();
//finalTable.TableName = "Customers";
if (ds.Tables.Count > 0)
{
int i = 1;
DataTable firstTable = ds.Tables[0];
//firstTable.TableName = "Customers";
foreach (DataRow row in firstTable.Rows)
{
if (i == 5)
{
firstTable.NewRow();
i = 0;
}
finalTable.Rows.Add(row.ItemArray);
i++;
}
}
Repeater1.DataSource = finalTable;
Repeater1.DataBind();
con.Close();
and if i used this finalTable.Rows.Add(row), it gives me "This row already belongs to another table".
con.Open();
cmd.Connection = con;
cmd.CommandText = "SELECT CustomerName FROM Customers";
SqlDataAdapter adp = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
adp.Fill(ds);
DataTable finalTable = new DataTable();
//finalTable.TableName = "Customers";
if (ds.Tables.Count > 0)
{
int i = 1;
DataTable firstTable = ds.Tables[0];
//firstTable.TableName = "Customers";
foreach (DataRow row in firstTable.Rows)
{
if (i == 5)
{
firstTable.NewRow();
i = 0;
}
finalTable.Rows.Add(row);
i++;
}
}
Repeater1.DataSource = finalTable;
Repeater1.DataBind();
con.Close();
}
don't know how to solve it, any solution please?
below is a method that allow you select data from your database by TSQL (select * from table1 ...) then return as datatable and continue processing (eg , bind table)
This is how
1) built a connection string , If you are developing web apps , go to web.config file add below , change parameter according your SQL environment setup.
<configuration>
<connectionStrings>
<add name="PSDatabaseConnectionString" connectionString="Data Source=YourSQLserverName\SQLEXPRESS;Initial Catalog=YourDatabaseName;Integrated Security=True" providerName="System.Data.SqlClient"/>
</connectionStrings>
....
2) then build a method to accept SQL statement and return multiple rows data as datatable . In below code , you do not need to define your datatable column structure , SQL will dynamic built it based on your SQL select statement
public static DataTable RunSQL_DML_FillDataGrid(string TSQL)
{
string connectionString = ConfigurationManager.ConnectionStrings["PSDatabaseConnectionString"].ConnectionString;
SqlDataAdapter dataAdapter;
SqlConnection conn = new SqlConnection(connectionString);
try
{
// Run TSQL on SQL server
dataAdapter = new SqlDataAdapter(TSQL, connectionString);
// MS Term ' Create a command builder to generate SQL update, insert, and
// delete commands based on selectCommand. These are used to
// update the database.
SqlCommandBuilder commandBuilder = new SqlCommandBuilder(dataAdapter);
// Populate a new data table and return the table.
// MS Term ' Populate a new data table and bind it to the BindingSource.
DataTable table = new DataTable();
table.Locale = System.Globalization.CultureInfo.InvariantCulture;
dataAdapter.Fill(table);
return table;
}
catch
{
return null;
}
}
3) Finally , you can bind your data table to other object ( datagridview , datatable ....) . I do not know what object type is Repeater1 inside your code but if it can accept datatable , then it shall bind correctly using the returned datatable

Modifying DataTable which is part of DataSet in C# - changes not showing in DataSet

I'm working in C# and I have a DataSet and a DataTable. I've added the DataTable to the DataSet. Then I populate the DataTable with a SQL query. In the debugger, I can see data in my DataTable. I see my DataTable in the DataSet's list of tables, but it's a null table (i.e., no columns, no data). Why is the data not showing up? Here's my code:
DataSet ds = new DataSet();
DataTable dt = new DataTable("BaseData");
ds.Tables.Add(dt);
List<SqlParameter> paramz = new List<SqlParameter>();
paramz.Add(new SqlParameter("#LitHoldDetailsID", litHoldDetailsID));
dt = LHClassLibrary.LHDataAccessLayer.ExecuteSelect("usp_GetLitHoldDetails_A", paramz);
I've tried
ds.AcceptChanges();
but that doesn't help. Do I really have to to define all the columns in the DataTable ahead of time? This is a query that returns a large number of columns, so I'm hoping I can skip that step.
You probably need to use SqlAdaptor.Fill(DataTable) like such:
string sql = #"Data Source=.;Initial Catalog=test;Integrated Security=True";
SqlConnection conn = new SqlConnection(sql);
conn.Open();
SqlDataAdapter adaptor = new SqlDataAdapter("<sql query>", conn);
DataTable dt = new DataTable();
adaptor.Fill(dt);
I will try to change the order of your code execution in this way
DataSet ds = new DataSet();
List<SqlParameter> paramz = new List<SqlParameter>();
paramz.Add(new SqlParameter("#LitHoldDetailsID", litHoldDetailsID));
DataTable dt = LHClassLibrary.LHDataAccessLayer.ExecuteSelect("usp_GetLitHoldDetails_A", paramz);
dt.TableName = "BaseData";
if(dt.DataSet != null) dt.DataSet.Tables.Remove(dt);
ds.Tables.Add(dt);
I suppose that the ExecuteSelect method will initialize and returns a DataTable with all the columns and rows returned by your stored procedure.
Only at this point the DataTable is added to your DataSet, not before.
In your code, the variable dt is assigned to a DataTable returned by ExecuteSelect but this is not the same reference to the DataTable created before and thus your DataSet remains with an empty table.
I always do it this way; hope this helps!
using (SqlConnection con = new SqlConnection(SqlConString))
{
string command = "Your Query Here...";
using (SqlCommand cmd = new SqlCommand(command, con))
{
cmd.Parameters.AddWithValue("#Param", SqlDbType.Type).Value = YourParameter;
con.Open();
using (SqlDataAdapter da = cmd.ExecuteNonQuery())
{
da.Fill(dt);
}
}
}

C#: Can't populate DataGridView programmatically

Rather than use the designer I'm trying to populate a DataGridView I've put on my Winform programmatically. When I look in the table under the debugger it has the correct columns and number of rows. The problem is the grid appears as an empty grey box on my form. When I bind the grid to the database via VS 2008 Designer it worked fine. How can I track down the problem?
UPDATE
I pretty much took this from this MSDN Article
UPDATE
Do I have to do anything in the designer other than drop the grid on the Winform?
using System;
using System.Data;
using System.Data.SqlClient;
using System.Data.SQLite;
using System.Windows.Forms;
namespace CC
{
public partial class Form1 : Form
{
private BindingSource bindingSource1 = new BindingSource();
private SQLiteDataAdapter dataAdapter = new SQLiteDataAdapter();
public Form1()
{
InitializeComponent();
dataGridView1 = new DataGridView();
this.Load += new System.EventHandler(Form1_Load);
this.Text = "Cars";
}
private void Form1_Load(object sender, EventArgs e)
{
dataGridView1.DataSource = bindingSource1;
GetData("select * from Cars");
}
private void GetData(string selectCommand)
{
string dbPath = "c:\\temp\\cars.db";
try
{
var connectionString = "Data Source=" + dbPath + ";Version=3";
dataAdapter = new SQLiteDataAdapter(selectCommand, connectionString);
SQLiteCommandBuilder commandBuilder = new SQLiteCommandBuilder(dataAdapter);
DataTable table = new DataTable();
table.Locale = System.Globalization.CultureInfo.InvariantCulture;
dataAdapter.Fill(table);
bindingSource1.DataSource = table;
// Resize the DataGridView columns to fit the newly loaded content.
dataGridView1.AutoResizeColumns(
DataGridViewAutoSizeColumnsMode.AllCellsExceptHeader);
}
catch (SqlException)
{
MessageBox.Show("To run this example, replace the value of the " +
"connectionString variable with a connection string that is " +
"valid for your system.");
}
}
}
}
I think you need to specify the DataMember property. And I think you don't require binding source object, directly you can bind DataTable to DataGridView control.
I am attaching a code which helps to bind gridview control with SQL Server database, and it works fine for me.
using(SqlDataAdapter sqlDataAdapter =
new SqlDataAdapter("SELECT * FROM Table1",
"Server=.\\SQLEXPRESS; Integrated Security=SSPI; Database=SampleDb"))
{
using (DataTable dataTable = new DataTable())
{
sqlDataAdapter.Fill(dataTable);
this.dataGridView1.DataSource = dataTable;
}
}
Sorry I don't have SQLite installed :(
basically i dont think u should complicate this! here's an easy way:
string cs = #"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=your db location;"; //connection string
string sql = "SELECT * FROM table_name"; //sql statment to display all data
OleDbConnection conn = new OleDbConnection(cs); //connectiion
OleDbDataAdapter da = new OleDbDataAdapter(sql, conn); //data adapter object
DataSet ds = new DataSet(); //dataset object to keep data in table
conn.Open(); //open connection
da.Fill(ds, "table_name"); // fill the dataset with table_name through data adapter
conn.Close(); //close connection
dataGridView1.DataSource = ds; //populate the datagridview with dataset
dataGridView1.DataMember = "table_name"; // populate datagridview with table_name
I have has difficulties with sqlite and also binding with linq. Now I have the same issue as above and ended up looping the data table to fill the grid.
I have noticed other minor issues with sqlite when using datatables and also databinding so I guess the problem lies with sqlite.
Here's some code to save time for anyone.
int rowcount = 0;
foreach (DataRow row in dataTable.Rows)
{
dataGrid.Rows.Add();
int column = 0;
foreach (var item in row.ItemArray)
{
dataGrid.Rows[rowcount].Cells[column].Value = item;
column++;
}
rowcount++;
}

How do I store multiple results from a stored procedure into a dataset?

How do I combine to result sets from a StoredProcedure into one dataset in ASP.NET?
Below is my code in asp.net
SqlDataAdapter adap = new System.Data.SqlClient.SqlDataAdapter("sp_Home_MainBanner_TopStory",con);
adap.SelectCommand.CommandType = CommandType.StoredProcedure;
adap.SelectCommand.Parameters.AddWithValue("#rows", 9);
DataSet DS = new DataSet();
adap.Fill(DS, "Table1");
adap.Fill(DS, "Table2");
GridView1.DataSource = DS.Tables["Table2"];
GridView1.DataBind();
Even if there were two adapters, how could I combine the results into one dataset?
In MS SQL we create a procedure like:
[ create proc procedureName
as
begin
select * from student
select * from test
select * from admin
select * from result
end
]
In C#, we write following code to retrieve these values in a DataSet
{
SqlConnection sqlConn = new SqlConnection("data source=(local);initial catalog=bj001;user id=SA;password=bj");
SqlCommand sqlCmd = new SqlCommand("procedureName", sqlConn);
sqlCmd.CommandType = CommandType.StoredProcedure;
sqlConn.Open();
SqlDataAdapter sda = new SqlDataAdapter(sqlCmd);
DataSet ds = new DataSet();
sda.Fill(ds);
sqlconn.Close();
// Retrieving total stored tables from a common DataSet.
DataTable dt1 = ds.Tables[0];
DataTable dt2 = ds.Tables[1];
DataTable dt3 = ds.Tables[2];
DataTable dt4 = ds.Tables[3];
// To display all rows of a table, we use foreach loop for each DataTable.
foreach (DataRow dr in dt1.Rows)
{
Console.WriteLine("Student Name: "+dr[sName]);
}
}
A DataSet contains Tables. For your above example, if you had two SqlDataAdapters, each calling a stored procedure and stored them like you did above.
adapter1.Fill(DS, "Table1");
adapter2.Fill(DS, "Table2");
This will take the table results from your first query and store it in the DataSet DS as Table1. It will then store another Table (Table2) in the same DataSet. To access these tables you use the following code:
DS.Tables["Table1"] //Or Table2, or whatever you name it during your Fill.
You already have the right process, you just need to look up how a DataSet works and decide how you want to call your information.
IF you want to combine your results into one DataTable however, you will need to iterate through the tables and combine information.
ex:
DataTable combinedTable = new DataTable();
//Create columns
foreach (DataRow row in DS.Tables["Table1"].Rows)
{
//Create rows? Copy information over? Whatever you want to do.
}
try using this:
adapter1.Fill(DS, "Table1, Table2");
this works here so...

c# datagridview and mysql

I am doing some c# and mysql and I was successful at getting mysql data into a grid view for the first time! Now, my main question is, how do I manage the grid view style with this? For example, say I have already created columns and such, how do I put the mysql data into a specific column in the grid view?
Below is the code that is actually loading the data into the grid view.
try
{
conn = new MySql.Data.MySqlClient.MySqlConnection(myConnectionString);
conn.Open();
// - DEBUG
// MessageBox.Show("Connection successful!");
MySqlDataAdapter MyDA = new MySqlDataAdapter();
MyDA.SelectCommand = new MySqlCommand("SELECT * FROM `swipes`", conn);
DataTable table = new DataTable();
MyDA.Fill(table);
BindingSource bSource = new BindingSource();
bSource.DataSource = table;
dataGridView1.DataSource = bSource;
}
catch (MySql.Data.MySqlClient.MySqlException ex)
{
MessageBox.Show(ex.Message);
Close();
}
Also, this creates columns based on the mysql data, how do I modify the width of these columns and such, or like stated above, use my own custom columns for my data? I've never done any mysql work in any UI, so I'm open to suggestions and tutorials as well. Thanks in advance!
If you really want to do this (as someone has already stated you should look at other options) you can create the columns in the designer and set the DataGridViewColumn.DataPropertyName on each column to the columns returned by the autogenerated dataset. Remember to turn of autogeneration of columns (AutoGenerateColumns) on the grid. This way you have full control of the column styles.
try this
string connection = "server=localhost;database=adil;user=root;password=";
MySqlConnection con = new MySqlConnection(connection);
con.Open();
MySqlCommand command = new MySqlCommand();
command.Connection = con;
MySqlDataAdapter MyDA = new MySqlDataAdapter();
string sqlSelectAll = "SELECT * from studentrec";
MyDA.SelectCommand = new MySqlCommand(sqlSelectAll, con);
DataTable table = new DataTable();
MyDA.Fill(table);
BindingSource bSource = new BindingSource();
bSource.DataSource = table;
dataGridView1.DataSource = bSource;

Categories