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);
Related
I'm trying to write a function -like Dcount and Dlookup in VBA Access- in a public class to use it everywhere in my project so I did the following :
public class MyTools
{
SqlConnection Cn = new SqlConnection(#"Server = AMR-PC\SQLEXPRESS ; Database=PlanningDB ; Integrated Security = True");
SqlDataAdapter da;
DataTable dt = new DataTable();
// DataView dv = new DataView();
SqlCommand cmd;
SqlDataReader DataRead;
// Variables
string MyColumn, MyTable, MyCondition,DlookResult;
int DcountResult;
// Methods & Functions
// Dcount
public int DCount(string MyColumn, string MyTable, string MyCondition)
{
da = new SqlDataAdapter("Select Count(#MyColumn) from #MyTable where #MyColumn = #MyCondition", Cn);
da.Fill(dt);
DcountResult = int.Parse(dt.Rows[0].ToString());
return DcountResult;
}
}
// Dlookup
}
And tried to use it like this :
int Result = DCount(txtColumn.Text, txtTable.Text, txtCond.Text);
txtResult.Text = null;
txtResult.Text = Result.ToString();
But it throws the error "Must declare the scalar variable "#MyColumn".
I tried to use sqlcommand and DataRead but I need to close the connection after the return and it became Unreachable or close before the return so it returns nothing , That's why i used SqlDataAdapter.
Thanks in advance .
It would have to look something more like this:
public class MyTools
{
private static string ConnectionString {get;} = #"Server = AMR-PC\SQLEXPRESS ; Database=PlanningDB ; Integrated Security = True";
public static int DCount(string MyTable, string MyColumn, string MyCondition)
{
string sql = $"Select Count({MyColumn}) from {MyTable} where {MyColumn} = #MyCondition";
using (var cn = new SqlConnection(ConnectionString))
using (var cmd = new SqlCommand(sql, cn))
{
cmd.Parameters.AddWithValue("#MyCondition", MyCondition);
cn.Open();
return (int)cmd.ExecuteScalar();
}
}
}
Just be aware this uses dynamic SQL, and is more than a little dangerous. In fact, you should not do this. I know you don't want to "keep typing SQL queries", but that might be exactly what you should do.
I have a class file where I declare readonly string of my query to be used in a method. I met the error of
Must declare the scalar variable "#DBID"
May I know if I declare my variables wrongly?
Below are the code snippets:
Class file:
private static readonly string QUERY_GETMATCHEDRECORD = "SELECT [Title], [ItemLink], [RecordDocID] FROM [ERMS].[dbo].[Records] WHERE [ID] = #DBID AND [V1RecordID] = #recID AND [V1RecordDocID] = #recDocID";
public DataTable GetMatchedRecord(string DBID, string recID, string recDocID)
{
string Method = System.Reflection.MethodBase.GetCurrentMethod().Name;
DataTable dt = new DataTable();
try
{
using (DB db = new DB(_datasource, _initialCatalog))
{
db.OpenConnection();
using (SqlCommand command = new SqlCommand())
{
string commandText = QUERY_GETMATCHEDRECORD .FormatWith(DBID,recID,recDocID);
_log.LogDebug(Method, "Command|{0}".FormatWith(commandText));
command.CommandText = commandText;
dt = db.ExecuteDataTable(command);
}
db.CloseConnection();
}
}
catch (Exception ex)
{
_log.LogError(Method, "Error while retrieving matching records |{0}".FormatWith(ex.Message));
_log.LogError(ex);
}
return dt;
}
Program .cs file:
MatchedRecords = oDB.GetMatchedRecord(DBID, RecID, RecDocID);
using '#'-notated variables will only work if you add the parameters to the commands parameter-collection.
try the following:
using (DB db = new DB(_datasource, _initialCatalog))
{
db.OpenConnection();
using (SqlCommand command = new SqlCommand())
{
command.CommandText = QUERY_GETMATCHEDRECORD;
command.Parameters.AddWithValue("#DBID", DBID);
command.Parameters.AddWithValue("#recID", recID);
command.Parameters.AddWithValue("#recDocID",recDocID);
dt = db.ExecuteDataTable(command);
}
db.CloseConnection();
}
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 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]);
}
}
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();
}