I have a main form which has an Add Teacher button and an Add subject button which directs them to their respective forms.The add teacher button works perfectly fine but when i click the add subject button it shows error: Cannot find table at position 1.I have been following the same procedure in add subject button as i did in add teacher button .Also I first added tbl_teachers table and then tbl_subjects table in my database ,so technically tbl_teachers should have index 0 right?Also when i click the Data Source section I only see it has only tbl_teachers.How do I update the data source? Thanks in advance.
try
{
SubjectConnect = new DatabaseConnection();
conString = Properties.Settings.Default.teachersConnectionString;
SubjectConnect.connection_string = conString;
SubjectConnect.sql = Properties.Settings.Default.SQL2;
ds = SubjectConnect.GetConnection;
Maxrows = ds.Tables[1].Rows.Count;
}
catch (Exception err)
{
MessageBox.Show(err.Message,"error");
}
class DatabaseConnection
{
private string sql_string;
private string strCon;
SqlDataAdapter da_1;
public string sql
{
set { sql_string = value; }
}
public string connection_string
{
set { strCon = value; }
}
public DataSet GetConnection
{
get { return MyDataset(); }
}
private DataSet MyDataset()
{
SqlConnection con = new SqlConnection(strCon);
con.Open();
da_1 = new SqlDataAdapter(sql_string, con);
DataSet dat_set = new DataSet();
da_1.Fill(dat_set,"Table_data_1");
con.Close();
return dat_set;
}
public void UpdateDatabase(DataSet ds)
{
SqlCommandBuilder cb = new SqlCommandBuilder(da_1);
cb.DataAdapter.Update(ds.Tables[0]);
}
}
Related
When I run the code, the required information does not appear in the gridbox.
{
public partial class fatura : Form
{
SqlConnection baglanti = new SqlConnection("Server=localhost;Database=master; Trusted_Connection=True");
DataTable tablo;
araba_ekleme araba_ekleme = new araba_ekleme();
public fatura()
{
InitializeComponent();
}
public DataTable listele(SqlDataAdapter adtr, string sorgu)
{
tablo = new DataTable();
adtr = new SqlDataAdapter(sorgu, baglanti);
adtr.Fill(tablo);
baglanti.Close();
return tablo;
}
private void onay_bekleyen()
{
string cumle = "declare #tc_no bigint select tc_no,car_plate,total,date,tax from [invoice] WHERE (status=0) AND tc_no=#tc_no";
SqlDataAdapter adtr2 = new SqlDataAdapter();
dg_pending.DataSource = listele(adtr2, cumle);
}
private void onaylanan()
{
string cumle = "declare #tc_no bigint select tc_no,car_plate,total,date,tax from [invoice] WHERE (status=1) AND tc_no=#tc_no";
SqlDataAdapter adtr2 = new SqlDataAdapter();
dg_done.DataSource = listele(adtr2, cumle);
}
private void fatura_Load(object sender, EventArgs e)
{
onay_bekleyen();
onaylanan();
}
}
}
When I run this code it gives an error. string cumle = "select tc_no,car_plate,total,date,tax from [invoice] WHERE (status=0) AND tc_no=#tc_no";
So i used this code block string cumle = "declare #tc_no bigint select tc_no,car_plate,total,date,tax from [invoice] WHERE (status=0) AND tc_no=#tc_no"; and when I run the code, the required information does not appear in the gridbox.
edit (SqlDataAdapter adtr, string sorgu) function like the code below:
1- You don't need to send SqlDataAdapter as input and define it inside the function.
2- You must open the connection.
3- Use using for SqlDataAdapter and SqlConnection so that there is no need to dispose.
4- Use try- catch to catch the error (In the following function, if there is an error, it will be displayed as a meesageBox. You can write error in file, console or anywhere else)
public DataTable listele(string sorgu)
{
DataTable tablo = new DataTable();
using (SqlConnection MyConnnection = new SqlConnection(conString ))
{
using (SqlDataAdapter dataAdapter = new SqlDataAdapter(sorgu, MyConnnection))
{
try
{
MyConnnection.Open();
dataAdapter.Fill(tablo);
}catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
return tablo;
}
define connection string:
public partial class fatura : Form
{
public string conString = "Server=localhost;Database=master; Trusted_Connection=True";
SqlConnection baglanti = new SqlConnection("Server=localhost;Database=master; Trusted_Connection=True");
DataTable tablo;
araba_ekleme araba_ekleme = new araba_ekleme();
...
Call the function as below:
dg_pending.DataSource = listele(cumle);
I am using two combo boxes in one of my programs. The first combo box contains the products while the second contains the categories. I have a method which loads he categories on the second combo box from the database when ever a new item is selected on the first combo box "products". The first time i run the program and select an item it loads from the database but if i try it again nothing loads. Please help with what might be causing this.
private void load_schemes(object sender, EventArgs e)
{
DataTable subjects = new DataTable();
DBConnect con = new DBConnect();
using (SqlConnection CONN = con.getConnection())
{
try
{
schemename.Items.Clear();
SqlDataAdapter adapter = new SqlDataAdapter();
String schemeType = schemetype.Text;
firstname.Text = schemetype.Text;
String SQL = "";
if (schemeType == "Family Scheme")
{
SQL = "select schemeID,SCHEMENAME from registration.familyMedicalScheme";
}
else if (schemeType == "Insurance Scheme")
{
SQL = "select schemeID,SCHEMENAME from registration.insurancescheme";
}
else if (schemeType == "Company Scheme")
{
SQL = "select schemeID,SCHEMENAME from registration.companymedicalscheme";
}
adapter.SelectCommand = new SqlCommand(
SQL, CONN);
adapter.Fill(subjects);
schemename.DataSource = subjects;
schemename.DisplayMember = "SCHEMENAME";
//schemename.ValueMember = subjects.;
}
catch (Exception ex)
{
// Handle the error
}
finally
{
CONN.Close();
}
}
}
I changed the solution and used Items.Add instead of data binding method and it is now working
adapter.Fill(subjects);
foreach (DataRow da in subjects.Rows)
{
schemename.Items.Add(da[0].ToString());
}
I have a project of type Windows Forms i Visual Studio 2010 Express.
I have created a service based local database and am able to show its data in textboxes on my Form and skipping through each of the records with buttons “Next” and “Previous”. So I have a connection to the database.
However, when I want to update the database with a new record with data from the textboxes when I click the Button “SAVE”, the data are only stored in the dataset and showed in the textboxes when I reach their position with the buttons, but not stored in the database. The next time I open the application, the new “stored” record is therefore gone.
Any idea where the error is in my code? Thanks a lot.
Here is the code for my save button in the file Form1.cs:
private void btnSave_Click(object sender, EventArgs e)
{
DataRow row = ds.Tables[0].NewRow();
row[1] = textBox1.Text;
row[2] = textBox2.Text;
row[3] = textBox3.Text;
row[4] = textBox4.Text;
ds.Tables[0].Rows.Add(row);
try
{
objConnect.UpdateDatabase(ds);
MaxRows += 1;
inc = MaxRows - 1;
MessageBox.Show("Database updated");
}
catch (Exception err)
{
MessageBox.Show(err.Message);
}
btnCancel.Enabled = false;
btnSave.Enabled = false;
btnAddNew.Enabled = true;
}
And here is the code for my class DatabaseConnection:
class DatabaseConnection
{
private string sql_string;
private string strCon;
private SqlDataAdapter da_1;
public string Sql { set { sql_string = value; } }
public string connection_string { set { strCon = value; } }
public DataSet GetConnection { get { return MyDataSet(); } }
private DataSet MyDataSet()
{
SqlConnection con = new SqlConnection(strCon);
con.Open();
da_1 = new SqlDataAdapter(sql_string, con);
DataSet dat_set = new System.Data.DataSet();
da_1.Fill(dat_set, "Table_Data_1");
con.Close();
return dat_set;
}
public void UpdateDatabase(System.Data.DataSet ds)
{
SqlCommandBuilder cb = new SqlCommandBuilder(da_1);
cb.DataAdapter.Update(ds.Tables[0]);
}
}
I'm creating a program that links to a database. On the main form when the user clicks a button 'Connect to Database', another form loads for the user to input the log-in details (server to connect to, username, and password). However, the connection isn't working for some reason. The error given is "Fill: SelectCommand.Connection property has not been initialized."
Here is my code so far:
public void connectDB_Click(object sender, EventArgs e)
{
DatabaseConnection dbConn = new DatabaseConnection();
if (dbConn.ShowDialog() == DialogResult.OK)
{
SqlConnectionStringBuilder connection = new SqlConnectionStringBuilder();
connection.DataSource = DatabaseConnection.dbNameText;
connection.UserID = DatabaseConnection.usernameText;
connection.Password = DatabaseConnection.passwordText;
SqlConnection con = new SqlConnection(connection.ToString());
using (SqlCommand command = new SqlCommand("Select name FROM sys.databases;"))
{
try
{
SqlDataAdapter sda = new SqlDataAdapter();
sda.SelectCommand = command;
DataTable table = new DataTable();
sda.Fill(table);
BindingSource source = new BindingSource();
source.DataSource = table;
dataGridDataBase.DataSource = source;
sda.Update(table);
this.dataGridDataBase.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill; //showing data onto the data grid view
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
}
Above is the code in the master class; the main form. Below is the code in the log-in form.
public partial class DatabaseConnection : Form
{
public static string dbNameText;
public static string usernameText;
public static string passwordText;
public bool buttonClicked = false;
public DatabaseConnection()
{
InitializeComponent();
password.PasswordChar = '•';
}
public void connectButton_Click(object sender, EventArgs e)
{
buttonClicked = true;
dbNameText = dbName.Text;
usernameText = username.Text;
passwordText = password.Text;
}
}
Any ideas, help, or solutions please?
You have to give connection to the command:
using (SqlCommand command = new SqlCommand("Select name FROM sys.databases;", con))
{
...
}
I'm starting with C # and I meet some problems.
I would like to know how to refresh the data, when I save data in the second windows form (agregar_en_directorio)
and want to display the new data in the combo box of the first windows form (generar_tarjeta).
The Conexion: conectaraBD.cs
public static SqlConnection ObtenerCOnexion()
{
SqlConnection Conn = new SqlConnection(#"Data source=MY-PC\SQLEXPRESS; Initial Catalog=myDatabase; User Id=user; Password=xxxx");
Conn.Open();
return Conn;
}
The Combo:
public void fillCombo()
{
string SQL = "select id_persona as identificador, clave_de_identificacion +' '+clave_de_la_dependencia +' '+grado_o_titulo+' '+nombre+' '+ ap+' '+ am DetallesCompletos from directorio";
DataTable dt = new DataTable();
using (SqlConnection Conn2 = conectaraBD.ObtenerCOnexion())
{
using (var cmd = new SqlCommand(SQL, Conn2))
{
try
{
dt.Load(cmd.ExecuteReader());
}
catch (SqlException e)
{
MessageBox.Show("Error al Cargar los Datos" + e.ToString(), "Error SQL",
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
comboDe.DataSource = dt;
comboDe.ValueMember = "identificador";
comboDe.DisplayMember = "DetallesCompletos";
}
Note: The used code for the combobox is the follow (used similars for the 3 combobox).
And would help me your opinion of the GUI
i solved, but I had to change some things:
public static DataTable dataFortheCombos()
{
DataTable dt = new DataTable();
SqlConnection connection = new SqlConnection(#"Data source=SAMANIEGO-PC\SQLEXPRESS; Initial Catalog=banco_de_datos; User Id=user; Password=xxx");/
string query = "select id_person as identifier, identification_key +' '+dependence_key +' '+degree_or_title+' '+name+' '+ ap+' '+ am as completedetails from directory";
SqlCommand cmd = new SqlCommand(query, connection);
SqlDataAdapter adap = new SqlDataAdapter(cmd);
adap.Fill(dt);
return dt;
}
public static AutoCompleteStringCollection autocompleteCombos()
{
DataTable dt = dataFortheCombos();
AutoCompleteStringCollection coleccion = new AutoCompleteStringCollection();
foreach (DataRow row in dt.Rows)
{
coleccion.Add(Convert.ToString(row["completedetails"]));
}
return coleccion;
}
public void fillCombos()
{
comboFrom.DataSource = dataFortheCombos();
comboFrom.DisplayMember = "completedetails"; //This is the value shown on the combo for the user
comboFrom.ValueMember = "identifier"; // The selectedc value insert as identifier (is a number)
comboFrom.SelectedIndex = -1; //Clear the combo
//NOTE -> The others combos (urned over and sender) using the same data
}
The event --onfocus-- is used to call the refresh when the user is located in the combobox comboFrom
private void comboDe_Enter(object sender, EventArgs e)
{
comboFrom.DataSource = null //Clear the Combo Box
//NOTE -> The others combos (urned over and sender) using the same data
fillCombos();
}