Accessing a dataset - "cannot find table 0" - c#

I have a method on a form for getting a dataset, which i'm trying to call to populate a combobox but the table is not being found. What am I missing?
Here's the dataset method...
public partial class frmForm2 : Form
{
#region Variables
//Connection string
string conString = ("Data Source=L008##\\#####; Initial Catalog=FiT; Integrated Security=SSPI;");
//Data Variables
int maxRows;
int userID = frmForm1.user_ID;
#endregion
#region SQL Conn & Dataset
public DataSet GetDataSet(string connectionString)
{
//Create connection object
SqlConnection sqlCon = new SqlConnection(connectionString);
SqlDataAdapter daAddWO = new SqlDataAdapter();
SqlCommand cmd = sqlCon.CreateCommand();
cmd.CommandText = ("SELECT user_ID, user_name FROM table WHERE user_id=#userID");
//Initialise the parameter
cmd.Parameters.AddWithValue("#userID", userID);
//Pass the SQL query to the da
daAddWO.SelectCommand = cmd;
//Create the dataset
DataSet dsAddWO = new DataSet();
maxRows = dsAddWO.Tables[0].Rows.Count;
//Open the connection and fill the dataset
sqlCon.Open();
daAddWO.Fill(dsAddWO);
sqlCon.Close();
//Return the dataset
return dsAddWO;
}
#endregion
And here's where I'm trying to call the method...
public frmForm2()
{
InitializeComponent();
try
{
//Request dataset
DataSet dsAddWO = GetDataSet(conString);
DataRow dRow;
int incRow = 0;
dRow = dsAddWO.Tables[0].Rows[incRow];
comboBox1.Text = dRow.ItemArray.GetValue(1).ToString();
}
catch (Exception err)
{
MessageBox.Show(err.Message);
}
}
Any help much appreciated!

You must access to table 0 after you fill the Dataset because when You create a new dataset, it has no tables.
e.g.
public DataSet GetDataSet(string connectionString)
{
//Create connection object
SqlConnection sqlCon = new SqlConnection(connectionString);
SqlDataAdapter daAddWO = new SqlDataAdapter();
SqlCommand cmd = sqlCon.CreateCommand();
cmd.CommandText = ("SELECT user_ID, user_name FROM table WHERE user_id=#userID");
//Initialise the parameter
cmd.Parameters.AddWithValue("#userID", userID);
//Pass the SQL query to the da
daAddWO.SelectCommand = cmd;
//Create the dataset
DataSet dsAddWO = new DataSet();
//Open the connection and fill the dataset
sqlCon.Open();
daAddWO.Fill(dsAddWO);
sqlCon.Close();
maxRows = dsAddWO.Tables[0].Rows.Count;
//Return the dataset
return dsAddWO;
}
Hope it helps
Bye

You try to access the table before the dataset has been filled. A new dataset will not contain any tables.

Related

Fill combobox from SQL database with specific parameter

I have problem to get specific value from sql server with parameter can anybody explain me why it works on winfom but not on wpf and how i can fix it
my code:
private void UpdateItems()
{
COMBOBOX1.Items.Clear();
SqlConnection conn = new SqlConnection(Properties.Settings.Default.constring.ToString());
SqlDataAdapter da = new SqlDataAdapter("SELECT * FROM CLIENT where cod_cli='some_specific_string'", conn);
DataSet ds = new DataSet();
da.Fill(ds, "CLIENT");
COMBOBOX1.ItemsSource = ds.Tables[0].DefaultView;
COMBOBOX1.DisplayMemberPath = ds.Tables[0].Columns["FR"].ToString();
COMBOBOX1.SelectedValuePath = ds.Tables[0].Columns["FC"].ToString();
}
The program when execute this function crash with error:
System.Data.SqlClient.SqlException: 'Invalid column name
'some_specific_string'.'
the solution is
SqlConnection sqlConnection = new SqlConnection(Properties.Settings.Default.constring.ToString());
{
SqlCommand sqlCmd = new SqlCommand("SELECT * FROM CLIENTS where cod_cli=#cod", sqlConnection);
sqlCmd.Parameters.AddWithValue("#cod", cod_cli.Text);
sqlConnection.Open();
SqlDataReader sqlReader = sqlCmd.ExecuteReader();
while (sqlReader.Read())
{
COMBOBOX1.Items.Add(sqlReader["FR"].ToString());
}
sqlReader.Close();
}
The query doesn't recognize string as parameter but adding as SQL parameter it works.
SqlConnection conn = new SqlConnection(Properties.Settings.Default.constring.ToString());
conn.Open();
SqlDataAdapter da = new SqlDataAdapter("SELECT * FROM CLIENT where cod_cli='some_specific_string'", conn);
DataSet ds = new DataSet();
da.Fill(ds, "CLIENT");
//Populate the combobox
COMBOBOX1.ItemsSource = ds.Tables[0].DefaultView;
COMBOBOX1.DisplayMemberPath = "FR";
COMBOBOX1.SelectedValuePath = "FC";
where "FR" and "FC" are existing columns in your SELECT Query.

C# filling a dataset from the database

I have some troubles with dataset in c#. I want to fill it with content from the database, but can't get it to work.
Here is my code:
from the main database layer containing the connection string
public static SqlCommand GetDbCommand(string sql)
{
if (dbconn.State.ToString().CompareTo("Open") != 0)
Open();
if (dbCmd == null)
{
dbCmd = new SqlCommand(sql, dbconn);
}
dbCmd.CommandText = sql;
return dbCmd;
}
This is the method that should fill the dataset from my DBMovie class
public static DataSet GetMovieSet()
{
DataSet movieSet = new DataSet();
string sql = "select * from Movie";
dbCmd = DBConnection.GetDbCommand(sql);
SqlDataAdapter da = new SqlDataAdapter();
da.Fill(movieSet);
DBConnection.Close();
return movieSet;
}
How do I connect the dataAdapter together with the database connection?
Connect the adapter to the command like so:
dbCmd = DBConnection.GetDbCommand(sql);
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = dbCmd; //Add this
da.Fill(movieSet);

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;

Saving edits to database made in datagridview

How can I adapt my code to any changes that are made remain persistent?
As I understand I need to update the datatable which in turn will update the database. So I have tried to use the update command like below on a button click event.
adb.Update(dt);
However this doesn't seem to work, so I am obviously missing something, but I'm not sure what?.
Code
String ConnStr = "Data Source=database.com\\sqlexpress; Initial Catalog=Data; User ID=mobile; Password=password";
String SQL = "SELECT stationID, LocationName, plandate, username, status FROM dbo.joblist WHERE username = #username and status = #status";
SqlConnection con = new SqlConnection(ConnStr);
try
{
con.Open();
}
catch (Exception)
{
MessageBox.Show(e.ToString());
}
SqlCommand command = new SqlCommand(SQL, con);
command.Parameters.Add("#username", SqlDbType.VarChar).Value = auditorCmb.Text;
command.Parameters.Add("#status", SqlDbType.VarChar).Value = statusCmb.Text;
SqlDataAdapter adb = new SqlDataAdapter(command);
using (DataTable dt = new DataTable())
{
try
{
adb.Fill(dt);
dataGridView1.AutoResizeColumns();
dataGridView1.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.AllCells;
con.Close();
}
catch
{
MessageBox.Show(e.ToString());
}
dataGridView1.DataSource = dt;
}
As far as I know SqlDataAdapter does not generate insert, update or delete commands on its own.
You have to either set them manually - https://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqldataadapter.selectcommand(v=vs.110).aspx.
Or generate them with SqlCommandBuilder:
public static DataSet SelectSqlRows(string connectionString,
string queryString, string tableName)
{
using (SqlConnection connection = new SqlConnection(connectionString))
{
SqlDataAdapter adapter = new SqlDataAdapter();
adapter.SelectCommand = new SqlCommand(queryString, connection);
SqlCommandBuilder builder = new SqlCommandBuilder(adapter);
connection.Open();
DataSet dataSet = new DataSet();
adapter.Fill(dataSet, tableName);
//code to modify data in DataSet here
builder.GetUpdateCommand();
//Without the SqlCommandBuilder this line would fail
adapter.Update(dataSet, tableName);
return dataSet;
}
}

Can't retrieve a specific item from a dataset

I've looked through the other questions related to this, but I'm having a different issue. I can't get a specific item to return, it only returns my column name. How do I get the item to return?
public static string GetOneFieldRecord(string field, string companyNum)
{
DataSet ds = new DataSet();
SqlCommand comm = new SqlCommand();
string strSQL = "SELECT #FieldName FROM Companies WHERE CompanyNum = #CompanyNum";
SqlConnection conn = new SqlConnection();
conn.ConnectionString = #connstring;
comm.Connection = conn;
comm.CommandText = strSQL;
comm.Parameters.AddWithValue("#FieldName", field);
comm.Parameters.AddWithValue("#CompanyNum", companyNum);
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = comm;
conn.Open();
da.Fill(ds, "CompanyInfo");
conn.Close();
return ds.Tables[0].Rows[0].ItemArray[0].ToString();
}
I've also tried
return ds.Tables[0].Rows[0][0].ToString();
I'm just getting whatever is in the field variable.
If I pass in ("CompanyName", 33), it returns "CompanyName".
Your query (in sql profiler) is
SELECT 'CompanyName' FROM Сompanies WHERE СompanyNum = 33
So it returns exactly "CompanyName" string. You cannot pass column name as sqlparameter. You should do something like
public static string GetOneFieldRecord(string field, string companyNum)
{
DataSet ds = new DataSet();
SqlCommand comm = new SqlCommand();
string strSQL = string.Format("SELECT {0} FROM Companies WHERE CompanyNum = #CompanyNum", field);
SqlConnection conn = new SqlConnection();
conn.ConnectionString = #connstring;
comm.Connection = conn;
comm.CommandText = strSQL;
comm.Parameters.AddWithValue("#FieldName", field);
comm.Parameters.AddWithValue("#CompanyNum", companyNum);
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = comm;
conn.Open();
da.Fill(ds, "CompanyInfo");
conn.Close();
return ds.Tables[0].Rows[0].ItemArray[0].ToString();
}
But this code can be used for SQL injection.
To avoid Sql injection, you could check that fieldName in field variable is one of the table columns.
Or You could get SELECT * FROM Сompanies WHERE СompanyNum = #CompanyNum and get value of named column from datatable:
public static string GetOneFieldRecord(string field, string companyNum)
{
DataSet ds = new DataSet();
SqlCommand comm = new SqlCommand();
string strSQL = "SELECT * FROM Companies WHERE CompanyNum = #CompanyNum";
SqlConnection conn = new SqlConnection();
conn.ConnectionString = #connstring;
comm.Connection = conn;
comm.CommandText = strSQL;
comm.Parameters.AddWithValue("#FieldName", field);
comm.Parameters.AddWithValue("#CompanyNum", companyNum);
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = comm;
conn.Open();
da.Fill(ds, "CompanyInfo");
conn.Close();
return ds.Tables[0].Rows[0][field].ToString();
}

Categories