DataGridView does not show SOME data - c#

I created an app for inserting specific data into database and it works fine.
However, when i try to view that data, DataGridView shows just some of those fields.
I stucked here. I tried to delete DataGridView and write code again, but it didn't helped.
private void displayData()
{
SqlConnection conn = new SqlConnection();
conn.ConnectionString = #"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\me\Documents\DataB.mdf;Integrated Security=True;Connect Timeout=30";
conn.Open();
SqlCommand cmd = conn.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "SELECT * FROM dbo.Users ";
cmd.ExecuteNonQuery();
DataGrid.Update();
DataSet dt = new DataSet();
SqlDataAdapter sda = new SqlDataAdapter(cmd);
sda.Fill(dt);
DataGrid.DataSource = dt;
conn.Close();
}
I expected completely filled DataGridView, but some fields are empty.
I can see name, username, date of birth, than 5 empty cells, then again i can see salary, education and so on..

Related

Updating Data GridView using the selected value inside the dropdown list

I have a dropdownlist and a gridview.. Dropdown list contains the list of the tables I have in my database. What I want is, when I select a particular table name from the dropdownlist, I want all the columns and data inside that particular table display inside the gridview.
This is my code...
Code for displaying the list of tables inside the dropdown is success.. But to bind the columns and data inside the gridview is not success..
Please Help me...
protected void Page_Load(object sender, EventArgs e)
{
using (SqlConnection con = new SqlConnection("Data Source=.\\SQLEXPRESS;Initial Catalog=Employee;Integrated Security=True"))
{
con.Open();
SqlCommand cmd = new SqlCommand("SELECT table_name FROM INFORMATION_SCHEMA.TABLES", con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
DropDownList1.DataSource = ds;
DropDownList1.DataTextField = "table_name";
DropDownList1.DataValueField = "table_name";
DropDownList1.DataBind();
con.Close();
}
}
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
using (SqlConnection con = new SqlConnection("Data Source=.\\SQLEXPRESS;Initial Catalog=Employee;Integrated Security=True"))
{
con.Open();
SqlCommand cmd = new SqlCommand("SELECT * FROM INFORMATION_SCHEMA.columns where table_name='+ DropDownList1.selecteditem.text +'", con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
GridView1.DataSource = ds;
//+DropDownList1.selecteditem.text +
GridView1.DataBind();
con.Close();
}
}
This is a bad idea on several levels. First you are wide open to SQL injection. Second, you are giving everyone full view access to every column and row of every table.
But the reason you are not getting data is because the select string does not make sense. It should look like this
"SELECT * FROM INFORMATION_SCHEMA.columns where table_name='" + DropDownList1.SelectedValue + "'"
But this is how a proper sql connection should look like.
//create a new datatable
DataTable dt = new DataTable();
//create the string that hold the query including token
string query = "SELECT * FROM INFORMATION_SCHEMA.columns where table_name = #TableName";
//create a new database connection
using (SqlConnection connection = new SqlConnection(ConnectionString))
using (SqlCommand command = new SqlCommand(query, connection))
{
command.CommandType = CommandType.Text;
//replace the token with the correct value
command.Parameters.Add("#TableName", SqlDbType.VarChar).Value = DropDownList1.SelectedValue;
//open the connection
connection.Open();
//load the data of the select into the datatable
dt.Load(command.ExecuteReader());
//bind the datatable to the gridview
GridView1.DataSource = dt;
GridView1.DataBind();
//but you can also skip the datatable and bind directly to the gridview
GridView1.DataSource = command.ExecuteReader();
GridView1.DataBind();
}

Displaying results of query to Oracle database in dataGrid

I am struggling to make my dataGrid viev results of query. Connection with database is fine. Here is sample of my code:
using (OracleConnection conn = new OracleConnection())
{
conn.ConnectionString = "properConnectionString"
conn.Open();
OracleCommand cmd = new OracleCommand();
cmd.Connection = conn;
cmd.CommandText = "select * FROM WORKERS";
cmd.CommandType = CommandType.Text;
OracleDataReader dr = cmd.ExecuteReader();
using (OracleDataAdapter orclDataAdapter = new OracleDataAdapter(cmd))
{
DataTable dt = new DataTable();
orclDataAdapter.Fill(dt);
dataGridView1.DataSource = dt;
}
}
Assuming that your call to the Oracle database is actually returning data, you're missing the databind statement on the gridview. Add this:
dataGridView1.DataBind();
place it right after the dataGridView1.DataSource = dt; line of code.

how to fill the cells of a DataGridView directly

I want to insert data directly in the cells of a datagrid and then send it to the database , but the rows are not being added with data, they remain empty after the insertion, despite the data appears in the cells.value when I run the code line by line using F11. The database is well linked to the datagrid because when I use textboxes to put the data in the datagrid cells, it works, but it doesn´t work when I put data directly in the cells, through the following code:
public void BD_Conexao()
{
try
{
OdbcConnection con = new OdbcConnection("driver= {MySQL ODBC 5.1 Driver};server=xxxx; database=lic; uid=estagio; password=1234; option = 3 ");
con.Open();
}
catch (Exception ex)
{
Console.WriteLine("Erro na ligação à base de dados. \n{0}", ex.Message);
return;
}
}
public void Consulta()
{
con = new OdbcConnection("driver= {MySQL ODBC 5.1 Driver};server=xxxx; database=lic; uid=estagio; password=1234; option = 3 ");
con.Open();
OdbcCommand Command = con.CreateCommand();
Command.CommandText = "select lojas.Id, lojas.NIF, lojas.Loja, lojas.Bloqueado, lojas.DataFim, lojas.lastupdate, lojas.Nome";
Command.CommandType = CommandType.Text;
Command.Connection = con;
OdbcDataAdapter adapter = new OdbcDataAdapter();
adapter.SelectCommand = Command;
DataSet dataSet = new DataSet();
adapter.Fill(dataSet);
grid_lic.DataSource = dataSet;
grid_lic.DataMember = dataSet.Tables[0].TableName;
}
private void bt_preencher_Click(object sender, EventArgs e)
{
BD_Conexao();
string DataFim = dateTimePicker.Value.ToString("yyyy-MM-dd");
string lastupdate = dateTimePicker2.Value.ToString("yyyy-MM-dd");
Commandtext = "insert into lojas (NIF,Loja,bloqueado, DataFim, lastupdate, Nome) values (#NIF,#Loja,#Bloqueado,#DataFim,#lastupdate,#Nome)";
OdbcCommand Command = new OdbcCommand(Commandtext, con);
Command.CommandType = CommandType.Text;
Command.Parameters.AddWithValue("#NIF", grid_lic.CurrentRow.Cells[1].Value);
Command.Parameters.AddWithValue("#Loja", grid_lic.CurrentRow.Cells[2].Value);
Command.Parameters.AddWithValue("#Bloqueado", checkBox_bloq.Checked);
Command.Parameters.AddWithValue("#DataFim", grid_lic.CurrentRow.Cells[4].Value);
Command.Parameters.AddWithValue("#lastupdate", grid_lic.CurrentRow.Cells[5].Value);
Command.Parameters.AddWithValue("#Nome", grid_lic.CurrentRow.Cells[6].Value);
Command.ExecuteNonQuery();
Consulta();
}
What is wrong?
data gird needs a data source property to fill data, so :
1) Insert all the data in database with your insert statement.
2) Then you need to do something like this to bind your data from database:
string connectionString = "Data Source=.;Initial Catalog=pubs;Integrated Security=True";
string sql = "SELECT * FROM Authors";
SqlConnection connection = new SqlConnection(connectionString);
SqlDataAdapter dataadapter = new SqlDataAdapter(sql, connection);
DataSet ds = new DataSet();
connection.Open();
dataadapter.Fill(ds);
connection.Close();
dataGridView1.DataSource = ds;

error while deleting row in gridview via 3 tier

Object reference not set to an instance of an object.
This is the error which i m getting while i trying to delete .. row from my grid view
this is in .. page_ load
gvDetails.DataSource =myBl.DeleteAllCountry(int.Parse(gvDetails.SelectedRow.ToString()));
on data access layer
public DataTable DeleteCountry(int country_id)
{
DataTable dltcontry = new DataTable();
SqlConnection con = new SqlConnection(#"Data Source=a8-pc\sqlexpress;Integrated Security=True");
SqlDataAdapter da;
try
{
SqlCommand cmd = new SqlCommand();
cmd.connection= con;
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "sp_DeleteCountry";
con.Open();
da = new SqlDataAdapter(cmd);
cmd.Parameters.AddWithValue("country_id", #country_id);
cmd.ExecuteNonQuery();
da.Fill(dltcontry);
con.Close();
}
and in business layer the code is like
public DataTable DeleteAllCountry(int country_id)
{
return mydtLayer.DeleteCountry(country_id);
}
First thing to correct, you need to set connection to your command
cmd.Connection =con;
or in the constructor as below
SqlCommand command = new SqlCommand(
queryString, connection);
Another problem is you try to convert selected gvDetails.SelectedRow to int value
check gvDetails.selectedRows.Count before you get value of selected row
if you have selection you can then get cell valu of your country_id column as below
gvDetails.SelectedRow.cells("country_id").Text
now you can convert this to a int value by using int.TryParse and if it is success send to your BL function to delete the record

Create/Display DataGrid from a table (database) C#

I'm trying show a DataGrid in C# (for app WindowsMobile). I have a database ("pruebaDB.sdf") in DataConnections and one table ("tablaMercancia").
Also in DataSource I have "pruebaDBDataSet" and "tablaMercancia".
How I can show data table in a DataGrid?
I use a SmartDevice project (I can't to use DataGridView, only I use DataGrid).
I can show a new table (created for code) in a DataGrid, but I don't know to show an existing table in my database.
string conSTR = "Data Source=" + (System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase)) + "\\pruebaDB.sdf;Persist Security Info=False";
SqlCeConnection connection = new SqlCeConnection(conSTR);
string sql = "SELECT * FROM tablaMercancia";
connection.Open();
SqlCeCommand cmd = new SqlCeCommand(sql, connection);
SqlCeDataAdapter da = new SqlCeDataAdapter(cmd);
//...............
//...Any idea?
//...............
connection.Close();
Any ideas please?
Thanks!!!
Please, Change Datagridview name as per below :
string conSTR = "Data Source=" + (System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase)) + "\\pruebaDB.sdf;Persist Security Info=False";
SqlCeConnection connection = new SqlCeConnection(conSTR);
string sql = "SELECT * FROM tablaMercancia";
connection.Open();
SqlCeCommand cmd = new SqlCeCommand(sql, connection);
SqlCeDataAdapter da = new SqlCeDataAdapter(cmd);
DataSet ds=new DataSet();
da.Fill(ds);
//datagridview1 is name of datagridview in form:
datagridview1.DataSource=ds.Tables[0];
connection.Close();
Try this.
string sql = "SELECT * FROM tablaMercancia";
connection.Open();
//SqlCeCommand cmd = new SqlCeCommand(sql, connection);
SqlCeDataAdapter da = new SqlCeDataAdapter(sql, connection);
DataSet ds=new DataSet();
da.Fill(ds);
designing page track the gridview or data grid
1st use namespace using System.Data,SqlClient;
sqlconnection con=new sqlconnection("string path");
con.open();
sqldataadapter da=new sqldataadapter("select * from emp",con);
dataset ds=new dataset();
da.fill(ds,"emp");
gridview1.datasource=ds;
gridview1.databind();

Categories