Not able to hold string from one form to other - c#

Able to show the database when c.Show() execute. When i close form 2 and click on the button6 the gridview on form 2 was empty. Any idea how to fix this bug?
Form 1:
private void System_btn_Click(object sender, EventArgs e)
{
OpenFileDialog openFileDialog1 = new OpenFileDialog();
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
Bitmap picture = new Bitmap(openFileDialog1.FileName);
ZoneStatus c = new ZoneStatus();
c.dbname = System.IO.Path.GetFileNameWithoutExtension(openFileDialog1.SafeFileName);
//c.Show();
}
}
private void button6_Click(object sender, EventArgs e)
{
ZoneStatus zoneStatus_form = new ZoneStatus();
zoneStatus_form.Show();
}
Form 2:
public string dbconnection;
public string dbname {get;set;}
private void ZoneStatus_Load(object sender, EventArgs e)
{
dbconnection = #"Data Source=" + dbname + ".db;Version=3;";
SQLiteConnection sqliteCon = new SQLiteConnection(dbconnection);
{
sqliteCon.Open();
// Create new DataAdapter
using (SQLiteDataAdapter a = new SQLiteDataAdapter(
"SELECT * FROM Alarm_Info", sqliteCon))
{
// Use DataAdapter to fill DataTable
DataTable dt = new DataTable();
a.Fill(dt);
dataGridView1.DataSource = dt; // to update my database
}
sqliteCon.Close();
}
}

change "public string dbname" to "public static string dbname".(same with dbconnection if you want to use that variable too.)
let's assume that you have declare your string in from1 and you want to use this string in form2 so your code will look like this.
form1:
public static string dbname;
in form2 create object of form1 and access this variable like this.
form2:
form1 objf1 = new form1();
string str=objf1.dbname;
now you can do whatever you want to do with variable dbname. you can assign to other variable like i did.

Related

is it possible to link a text box to a database?

i'm currently working on my C# "WindowForm" Project and i want to know if it's possible to link a textbox from any form to a database and update the textbox content from time to time so the users of my application would get up to dates information of what i'm willing to post in this form (textbox).
thank you,
If you want to refresh the text in real time from a datatable, you can try SqlDependency.
The following is a simple demo.
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
System.Data.SqlClient.SqlConnection conn = null;
System.Data.SqlClient.SqlCommand command = null;
// Set connection string
SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder
{
DataSource = #"datasource name",
// set database
InitialCatalog = #"catalog name",
// access the database using the existing windows security certificate
IntegratedSecurity = true
};
private void Form1_Load(object sender, EventArgs e)
{
conn = new System.Data.SqlClient.SqlConnection(builder.ConnectionString);
command = conn.CreateCommand();
command.CommandText = "select text from dbo.TableText where id<>20 order by id desc ";
// Start
SqlDependency.Start(builder.ConnectionString);
// Get data
GetData();
}
private void GetData()
{
command.Notification = null;
SqlDependency dependency = new SqlDependency(command);
dependency.OnChange += new OnChangeEventHandler(sqlDependency_OnChange);
using (SqlDataAdapter adapter = new SqlDataAdapter(command))
{
System.Data.DataSet ds = new DataSet();
adapter.Fill(ds, "test");
string text = ds.Tables["test"].Rows[0]["Text"].ToString();
textBox.Text = text;
}
}
void sqlDependency_OnChange(object sender, SqlNotificationEventArgs e)
{
// Because it is a child thread, you need to update the ui with the invoke method.
if (this.InvokeRequired)
{
this.Invoke(new OnChangeEventHandler(sqlDependency_OnChange), new object[] { sender, e });
}
else
{
SqlDependency dependency = (SqlDependency)sender;
dependency.OnChange -= sqlDependency_OnChange;
// After the notification, the current dependency is invalid, you need to re-get the data and set the notification.
GetData();
}
}
private void Form1_FormClosed(object sender, FormClosedEventArgs e)
{
// Clear resource
SqlDependency.Stop(builder.ConnectionString);
conn.Close();
conn.Dispose();
}
}
For more info about SqlDependency, you can refer to Detecting Changes with SqlDependency.
Hope this can help you.

Update datagridview from usercontrol using event button click form

I'm try to update datagridview in usercontrol using event buttonclick from another form. But i still can't resolve it.
I have form1, already display usercontrol in panel.
Code from usercontrol like this.
public partial class suppliers : UserControl
{
SqlConnection conn = new SqlConnection(#"Data Source=HENDRICK;Initial Catalog=mydb");
public void displaydata()
{
conn.Open();
DataTable dt = new DataTable();
SqlDataAdapter adp = new SqlDataAdapter("SELECT [id_supplier] as 'ID' ,[nama_supplier] as 'Nama' ,[telepon_supplier] as 'Telepon' ,[alamat_supplier] as 'Alamat' FROM[mydb].[dbo].[supplier]",conn);
adp.Fill(dt);
datagridsuppliers.DataSource = dt;
conn.Close();
}
public suppliers()
{
InitializeComponent();
displaydata();
}
private void btnaddsuppliers_Click(object sender, EventArgs e)
{
Form1 frm = new Form1();
new PopupEffect.transparentBg(frm, new addsuppliers());
}
}
When I click the btnaddsuppliers, the addsuppliers form will appear, that is useful for inserting data.
The code from addsuppliers form like this.
public partial class addsuppliers : Form
{
SqlConnection conn = new SqlConnection(#"Data Source=HENDRICK;Initial Catalog=mydb");
suppliers supp = new suppliers();
void reset_txtbox()
{
txtnama.Text = "";
txttelepon.Text = "";
txtalamat.Text = "";
}
public addsuppliers()
{
InitializeComponent();
}
private void btnadd_Click(object sender, EventArgs e)
{
try
{
conn.Open();
String insertQuery = "insert into [mydb].[dbo].[supplier] ([id_supplier],[nama_supplier],[telepon_supplier],[alamat_supplier]) values (#id,#nama,#telepon,#alamat)";
cmd = new SqlCommand(insertQuery, conn);
cmd.Parameters.AddWithValue("#id", "SP1");
cmd.Parameters.AddWithValue("#nama", txtnama.Text);
cmd.Parameters.AddWithValue("#telepon", txttelepon.Text);
cmd.Parameters.AddWithValue("#alamat", txtalamat.Text);
cmd.ExecuteNonQuery();
conn.Close();
Bunifu.Snackbar.Show(this.FindForm(), "Add Supplier Successfully.", 2000, Snackbar.Views.SnackbarDesigner.MessageTypes.Success);
supp.displaydata();
reset_txtbox();
}
catch
{
Bunifu.Snackbar.Show(this.FindForm(), "Failed,Check database connection.", 2000, Snackbar.Views.SnackbarDesigner.MessageTypes.Error);
}
}
}
}
The problem is when btnadd is clicked, the database has been updated but the datagridview on usercontrol is not updated automatically.
I have tried to use the call displaydata() function to update the DataGridView. But the result of DataGridView remains unchanged or not updated.
Please help to resolve this problem. Thank You.

Sending data between 2 forms

I have form1 with datagridview and a button. When i click a button, a new form opens up where there is a textbox and also a button. In this textbox i can write query and with a click of a button query results are shown in form1 datagridview. The problem is that it opens up another instance of form1 , but i would like that form1 stays open the whole time and only records in datagridview are changing, according to the query input in form2. Both form1 and form2 needs to be opened and active when called.
Here is my code:
//FORM 1
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
var queryForm = new Form2();
queryForm.Show(this);
}
//FORM 2
public Form2()
{
InitializeComponent();
}
private SqlConnection Conn;
private void Form1_Load(object sender, EventArgs e)
{
Conn = new SqlConnection(#"Data Source=srvr;Initial Catalog =db; User ID =user; Password =pass");
}
private void btnExecute_Click(object sender, EventArgs e)
{
Form1 frm1 = new Form1();
frm1.Show(this);
frm1.Activate();
SqlCommand cmd = new SqlCommand();
cmd.Connection = Conn;
cmd.CommandText = txtQuery.Text;
try
{
Conn.Open();
SqlDataReader reader = cmd.ExecuteReader();
frm1.dataGridView1.Columns.Clear();
frm1.dataGridView1.Rows.Clear();
if (reader.HasRows)
{
DataTable schema = reader.GetSchemaTable();
int field_num = 0;
foreach (DataRow schema_row in schema.Rows)
{
int col_num = frm1.dataGridView1.Columns.Add(
"col" + field_num.ToString(),
schema_row.Field<string>("ColumnName"));
field_num++;
frm1.dataGridView1.Columns[col_num].AutoSizeMode =
DataGridViewAutoSizeColumnMode.AllCells;
}
object[] values = new object[reader.FieldCount];
while (reader.Read())
{
reader.GetValues(values);
frm1.dataGridView1.Rows.Add(values);
}
}
}
catch (Exception ex)
{
MessageBox.Show("Error executing command.\n" + ex.Message);
}
finally
{
Conn.Close();
}
}
Well, since you are calling Form1 frm1 = new Form1(); - what else did you expect than opens up another instance of form1 ? - Why should new Form1() not produce another instance?
You will need to get the reference of the already created Form1.
See this for example
Find the open forms in c# windows application
When you found it you can activate it for example:
var frm1 = Application.OpenForms[0];
//frm1.Show(this); <- don't need to call Show since its already open
frm1.Activate();
Also you should change your btnExecute_Click to this.
private void btnExecute_Click(object sender, EventArgs e)
{
var frm1 = Application.OpenForms[0] as Form1; //find `Form1` like you want, I only take [0]
//always create a new instance of SqlConnection here and dispose it with the using Keyword
//don't use a private field to try to keep the Connection, let the internal Connection pool handle that case
using (var con = new SqlConnection(#"Data Source=srvr;Initial Catalog =db; User ID =user; Password =pass"))
{
try
{
con.Open();
//clean up, Command/Reader with using keyword
using (var cmd = con.CreateCommand())
{
cmd.CommandText = txtQuery.Text;
using (SqlDataReader reader = cmd.ExecuteReader())
{
//read data
}
}
}
catch (Exception ex)
{
MessageBox.Show("Error executing command.\n" + ex.Message);
}
}
//should activate the `Form1` AFTER the job is done, you can consider if you only want to activate it if the previous Code didn't fail
frm1.Activate();
}
Don't really get what you are doing in your "read_data" routine.
This Code block:
frm1.dataGridView1.Columns.Clear();
frm1.dataGridView1.Rows.Clear();
if (reader.HasRows)
{
DataTable schema = reader.GetSchemaTable();
int field_num = 0;
foreach (DataRow schema_row in schema.Rows)
{
int col_num = frm1.dataGridView1.Columns.Add(
"col" + field_num.ToString(),
schema_row.Field<string>("ColumnName"));
field_num++;
frm1.dataGridView1.Columns[col_num].AutoSizeMode =
DataGridViewAutoSizeColumnMode.AllCells;
}
object[] values = new object[reader.FieldCount];
while (reader.Read())
{
reader.GetValues(values);
frm1.dataGridView1.Rows.Add(values);
}
}
Try if the following is sufficient, replace my comment "//read data" in the above code with this:
frm1.dataGridView1.AutoGenerateColumns = true; //say to automatically create columns, based on the result inside the datatable
frm1.dataGridView1.Columns.Clear();
var dataTable = new DataTable();
dataTable.Load(dataReader); //load the SqlDataReader into the DataTable
frm1.dataGridView1.DataSource = dataTable; //set the dataGridView's DataSource to the dataTable
On button click in form1, you can simply open a new instance of form2 and do your work there and on closing receive that value in form1. Or you can pass the instance of your form1 into form2 via constructor and update form1 from form2. For example:
var isFormClosed = false;
using(form1 frm = new form1())
{
// do something here
frm.ShowDialog();
isFormClosed = true;
}
Or, if you prefer to pass the reference of form1 into form2,
var isFormClosed = false;
using(form1 frm = new form1(this))
{
// do something here
frm.ShowDialog();
isFormClosed = true;
}
Here, in form2, you can simply use the passed reference of form1 to update properties or grids.

How to pass a value from one Form to a private TextBox in another Form?

I have Form1 with several private TextBoxes. I want to pass some values from my DataGridView in Form2 to those TextBoxes inForm1 (when I press Enter for example).
What I want to do is to pass the values of rows of current selected Row in DataGridView to be passed to TextBoxes in Form1:
(I know how to get the values of selected row in datagridview my question is just the title...)
if (e.KeyCode == Keys.Enter)
{
SqlCommand sqlcmd = new SqlCommand("SELECT ID FROM X WHERE ID=" +
dataGridView1.CurrentRow.Cells[0].Value + "", sqlcon);
SqlDataReader sqldr = sqlcmd.ExecuteReader();
while (sqldr.Read())
{
Form1.CodeTextBox = sqldr[codecolumn].Tostring
Form1.NameTextBox = sqldr[Namecolumn].Tostring
Form1.BlahTextBox = sqldr[Blahcolumn].Tostring
}
}
which yells at me:
codeTextBox is private... not able to do so because of protection
level...
I think I have to make a static class to do so, but I dont know how.
I would appriciate if someone would explain me that.
Form1 Class:
public partial class Form1 : Form
{
public static string searchString;
SqlConnection sqlcon =
new SqlConnection("Data Source=(LocalDB)\\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\\Database1.mdf;Integrated Security=True");
public Form1()
{
InitializeComponent();
SqlDataAdapter sqlda = new SqlDataAdapter("GetInvoice", sqlcon);
DataTable dt = new DataTable();
sqlda.Fill(dt);
dataGridView1.DataSource = dt;
}
//Xbuton_click datagridview_blah ...
}
Declare private variable and Form1 Constructor with parameter like :
private string CodeTextBox; private string NameTextBox; private string BlahTextBox;
Public Form1(string CodeTextBox , string NameTextBox, string BlahTextBox)
{
this.CodeTextBox= CodeTextBox;
this.NameTextBox= NameTextBox;
this.BlahTextBox = BlahTextBox;
}
Assign Value to Textbox
txtCodeTextBox.Text = CodeTextBox;
txtNameTextBox.Text = NameTextBox;
txtBlahTextBox.Text = BlahTextBox;
Call it like
if (e.KeyCode == Keys.Enter)
{
SqlCommand sqlcmd = new SqlCommand("SELECT ID FROM X WHERE ID=" + dataGridView1.CurrentRow.Cells[0].Value + "", sqlcon);
SqlDataReader sqldr = sqlcmd.ExecuteReader();
while (sqldr.Read())
{
string CodeTextBox = sqldr[codecolumn].Tostring;
string NameTextBox = sqldr[Namecolumn].Tostring;
string BlahTextBox = sqldr[Blahcolumn].Tostring;
Form1 frm = new Form1(CodeTextBox, NameTextBox, BlahTextBox);
}
}
try this
CodeTextBox text changed event
public void CodeTextBox_TextChanged(object sender, EventArgs e)
{
CodeTextBox.Text = ((TextBox)sender).Text;
}
SqlDataReader
while (sqldr.Read())
{
Form1 form1 = new Form1();
TextBox t = new TextBox();
t.Text=sqldr[codecolumn].Tostring;
form1.CodeTextBox_TextChanged(t,null);
}

Update SQL query, unsure why it isn't working as no errors are appearing

I have been staring at this UPDATE statement for a long while and are unsure why my table isn't changing. When I press the button no error appears but my table doesn't not get updated either, I have checked that all of my variables have values on debug and they do.
I'd appreciate any help anyone can give me!
This is the code that contains the statement I need help with:
private void button1_Click(object sender, EventArgs e)
{
string studentanswertext = textBox1.Text;
string connectionString = ConfigurationManager.ConnectionStrings["myconnectionstring"].ConnectionString;
string y = GlobalVariableClass.Signedinteacher;
Convert.ToInt32(y);
MessageBox.Show(y);
MessageBox.Show(Convert.ToString(CurrentQuestionID));
MessageBox.Show(studentanswertext);
SqlConnection connect = new SqlConnection(connectionString);
connect.Open();
SqlCommand command20 = new SqlCommand(#"UPDATE QuestionStudentAssociation SET ([StudentAnswer]=#StudentAnswertext) WHERE ([QuestionID]=#CurrentQID AND [StudentID]=#SignedinStudent )", connect);
command20.Parameters.AddWithValue("#StudentAnswertext", studentanswertext);
command20.Parameters.AddWithValue("#CurrentQID", CurrentQuestionID);
command20.Parameters.AddWithValue("#SignedinStudent", y);
command20.BeginExecuteNonQuery();
connect.Close();
}
This is the whole code for my form if anyone wanted to look at it just in case that is affecting the button even handler:
namespace ComputingA2_Official_Project
{
public partial class CurrentlySetTestForm : Form
{
Timer loopTimer = new Timer();
private int CurrentQuestionID { get; set; }
private string QuestionSpace { get; set; }
public CurrentlySetTestForm()
{
InitializeComponent();
}
private void CurrentlySetTestForm_Load(object sender, EventArgs e)
{
string y = GlobalVariableClass.Signedinteacher;
Convert.ToInt32(y);
string connectionString = ConfigurationManager.ConnectionStrings["myconnectionstring"].ConnectionString;
SqlConnection connect = new SqlConnection(connectionString);
connect.Open();
SqlCommand command18 = new SqlCommand("SELECT MIN([QuestionID]) AS QuestionID FROM QuestionStudentAssociation WHERE ( [StudentID]=#Signedinstudent AND [StudentAnswer] IS NULL )", connect);
command18.Parameters.AddWithValue("#Signedinstudent", y);
var reader = command18.ExecuteReader();
while (reader.Read())
{
CurrentQuestionID = Convert.ToInt32(reader[0]);
SqlCommand command19 = new SqlCommand("SELECT ([Question Space]) FROM Questions WHERE ([QuestionID]=#CurrentQID)", connect);
command19.Parameters.AddWithValue("#CurrentQID", CurrentQuestionID);
using (SqlDataReader reader2 = command19.ExecuteReader())
{
while (reader2.Read())
{
QuestionSpace = Convert.ToString(reader2[0]);
label1.Text = QuestionSpace;
}
}
}
connect.Close();
}
private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
}
private void button1_Click(object sender, EventArgs e)
{
string studentanswertext = textBox1.Text;
string connectionString = ConfigurationManager.ConnectionStrings["myconnectionstring"].ConnectionString;
string y = GlobalVariableClass.Signedinteacher;
Convert.ToInt32(y);
MessageBox.Show(y);
MessageBox.Show(Convert.ToString(CurrentQuestionID));
MessageBox.Show(studentanswertext);
SqlConnection connect = new SqlConnection(connectionString);
connect.Open();
SqlCommand command20 = new SqlCommand(#"UPDATE QuestionStudentAssociation SET ([StudentAnswer]=#StudentAnswertext) WHERE ([QuestionID]=#CurrentQID AND [StudentID]=#SignedinStudent )", connect);
command20.Parameters.AddWithValue("#StudentAnswertext", studentanswertext);
command20.Parameters.AddWithValue("#CurrentQID", CurrentQuestionID);
command20.Parameters.AddWithValue("#SignedinStudent", y);
command20.BeginExecuteNonQuery();
connect.Close();
}
private void timer1_Tick(object sender, EventArgs e)
{
}
}
}
I believe the issue is that you are executing the command asynchronously (BeginExecuteNonQuery), but never calling EndExecuteNonQuery to commit it. I also suspect you could just call it synchronously like this:
command20.ExecuteNonQuery();

Categories