I have a program that inserts some values from text boxes into database. The problem is that the values are stored successfully into db but I can't get them into my Data Grid View...here's the code:
public void LoadMuzee(DataGridView table)
{
SqlConnection conn = new SqlConnection(#"Data Source=.\SQLEXPRESS;" + "Initial Catalog=lista_muzee;Integrated Security=SSPI;");
SqlCommand cmd = new SqlCommand("SELECT muzee.*, gen.gen_nume " +
"FROM muzee INNER JOIN gen " +
"ON muzee.muz_gen_id = gen.gen_id", conn);
SqlDataAdapter sa = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
conn.Open();
sa.Fill(dt);
conn.Close();
sa.Dispose();
cmd.Dispose();
conn.Dispose();
table.DataSource = dt;
table.Columns["muz_id"].Visible = false;
table.Columns["muz_gen_id"].Visible = false;
}
public frmMuzee()
{
InitializeComponent();
LoadMuzee(dgvMuzee);
}
your not performing databind on your gridview which causes data not get binded into gridview
table.databind()
Related
I am trying to make a feedback form where I want to show the name which is inserted n number of times.
My DataBase has for example 9 duplicate names as feedback was input for that same person 9 times and I want to display it on the result that common name.
Please help me out to complete the code/solution or Correct the code and get the result.
SQL QUERY IS RUNNING PROPERLY IT IS SELECTING THE SINGLE DATA FROM DATABASE BUT HOW TO SHOW THIS ON WEBPAGE
public void cal_F2name()
{
string oracledb = "Data Source=(DESCRIPTION =(ADDRESS = (PROTOCOL = TCP****))(****))(CONNECT_DATA =(SERVER = DEDICATED)(SID = ORCL));";
OracleConnection conn = new OracleConnection(oracledb);
conn.Open();
OracleCommand cmd = new OracleCommand();
cmd.Connection = conn;
OracleDataAdapter da1 = new OracleDataAdapter();
DataTable dt1 = new DataTable();
DataSet ds1 = new DataSet();
cmd.CommandText = "SELECT DISTINCT (F2NAME) FROM CMDC_FEEDBACK WHERE PRG_NAME ='" + cb_prg_name.SelectedValue + "'";
da1.SelectCommand = cmd;
da1.Fill(ds1);
name = Convert.ToString(ds1.Tables[0].Rows[0][0].ToString());
Label58.Text = String.Format("{0:0.00}",name);
conn.Close();
}
try using below code, i have made some change in sql query to get only single record as result.
public void cal_F2name()
{
string oracledb = "Data Source=(DESCRIPTION =(ADDRESS = (PROTOCOL = TCP****))(****))(CONNECT_DATA =(SERVER = DEDICATED)(SID = ORCL));";
OracleConnection conn = new OracleConnection(oracledb);
conn.Open();
OracleCommand cmd = new OracleCommand();
cmd.Connection = conn;
OracleDataAdapter da1 = new OracleDataAdapter();
DataTable dt1 = new DataTable();
DataSet ds1 = new DataSet();
cmd.CommandText = "SELECT max(DISTINCT (F2NAME)) FROM CMDC_FEEDBACK WHERE PRG_NAME ='" + cb_prg_name.SelectedValue + "' AND F2NAME<>'' AND F2NAME IS NOT NULL" ;
da1.SelectCommand = cmd;
da1.Fill(ds1);
name = Convert.ToString(ds1.Tables[0].Rows[0][0].ToString());
Label58.Text = String.Format("{0:0.00}",name);
conn.Close();
}
i have not check but it will work, if you result binding to lable is correct.
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();
}
I'm trying to initialize a DataGridView object. All I did was add the object to my screen without changing any properties. I have code that is run when the user selects the panel it is on. The code looks like this...
DataTable tbl = new DataTable();
string query = "SELECT viewfolder, status FROM Folders WHERE username = '" + Globals.usrName + "' ORDER BY viewfolder";
SqlConnection connect = new SqlConnection(#"Data Source=(LocalDB)\v11.0;" +
#"AttachDbFilename=C:\Development\C-Sharp\LockItUp\Lockitup.mdf;Integrated Security=True");
SqlCommand cmd = new SqlCommand(query, connect);
connect.Open();
try
{
SqlDataAdapter dAdapt = new SqlDataAdapter(cmd);
dAdapt.Fill(tbl);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
return;
}
connect.Close();
dataGridView1.DataSource = tbl;
So is there any other code I have to add or properties I have to set to see the data appear on the grid? Thanks for the help.
Can you try using this code:
void FillData()
{
using (SqlConnection c = new SqlConnection(
#"Data Source=(LocalDB)\v11.0;" +
#"AttachDbFilename=C:\Development\C-Sharp\LockItUp\Lockitup.mdf;Integrated Security=True"))
{
c.Open();
string query = "SELECT viewfolder, status FROM Folders WHERE username = '" + Globals.usrName + "' ORDER BY viewfolder";
using (SqlDataAdapter a = new SqlDataAdapter(
query , c))
{
DataTable tbl = new DataTable();
a.Fill(tbl);
dataGridView1.DataSource = tbl;
}
}
}
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;
I have a bit of an issue when it comes to updating view in datagridview. My function successfully deletes selected row from database but DataAdapter does not fill datatable dt. Function with the same structure works perfectly when adding rows.
private string ConString;
private SQLiteCommand cmd;
DataTable dt = new DataTable();
SQLiteConnection sql_con;
SQLiteDataAdapter DB;
// Function to delete rows
public void DeleteRow(string value)
{
string sqlStatement = "DELETE FROM Trades WHERE ID = " + value;
try
{
sql_con = new SQLiteConnection(ConString);
sql_con.Open();
cmd = sql_con.CreateCommand();
cmd.CommandText = sqlStatement;
cmd.ExecuteNonQuery();
DB = new SQLiteDataAdapter();
dt.Clear();
DB.Fill(dt);
}
finally
{
sql_con.Close();
}
}