I have two tables in my database. Let's say table A and table B. table A values are put in checkedlistbox. The selected values in checkedlistbox then are put into table B. I tried to make a code however it wont work. Do you have any idea on how to make this problem work?
thanks ahead guys.
by the way im using c#.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Npgsql;
namespace WindowsFormsApplication1
{
public partial class Form8 : Form
{
public Form8()
{
InitializeComponent();
this.Load += Form8_Load;
button2.Click += button2_Click;
}
private void Form8_Load(object sender, EventArgs e)
{
string connstring = ("Server=localhost;Port=5432;User Id=postgres;Password=021393;Database=postgres;");
NpgsqlConnection conn = new NpgsqlConnection(connstring);
NpgsqlCommand cmd = new NpgsqlCommand("SELECT conname FROM condition", conn);
cmd.CommandType = CommandType.Text;
conn.Open();
using (NpgsqlDataAdapter da = new NpgsqlDataAdapter(cmd))
{
DataTable dt = new DataTable();
da.Fill(dt);
((ListBox)checkedListBox1).DataSource = dt;
((ListBox)checkedListBox1).DisplayMember = "conname";
((ListBox)checkedListBox1).DisplayMember = "conid";
string[] condition = dt.Rows[0]["conname"].ToString().Split(',');
}
}
private void button2_Click(object sender, EventArgs e)
{
string connstring = ("Server=localhost;Port=5432;User Id=postgres;Password=021393;Database=postgres;");
NpgsqlConnection conn = new NpgsqlConnection(connstring);
NpgsqlCommand cmd = new NpgsqlCommand("Insert into famhistory(famid) Values (#famid)", conn);
conn.Open();
cmd.Parameters.AddWithValue("#famid", checkedListBox1.Text);
cmd.ExecuteNonQuery();
MessageBox.Show("Data has been saved");
conn.Close();
}
}
}
You have to iterate through all the selected items:
//check if any item is selected
if (checkedListBox1.SelectedItems.Count > 0)
{
//connect to database
string connstring = ("Server=localhost;Port=5432;User Id=postgres;Password=021393;Database=postgres;");
NpgsqlConnection conn = new NpgsqlConnection(connstring);
conn.Open();
//loop through all selected items
foreach (object item in checkedListBox1.CheckedItems)
{
//convert item to string
string checkedItem = item.ToString();
//insert item to database
NpgsqlCommand cmd = new NpgsqlCommand("Insert into famhistory(famid) Values (#famid)", conn);
cmd.Parameters.AddWithValue("#famid", checkedItem); //add item
cmd.ExecuteNonQuery();
}
//close connection
conn.Close();
MessageBox.Show("Data has been saved");
}
Note: I am executing all insert commands in one open connection, because opening and closing connection frequently is not best practice.
Related
Update should be updating the data in the confirm table with the given parameters. However no input gets updated/inputted despite there being no errors.
When the exact same query is inputted into the SQL Server Management Studio there is no errors and the rows are updated.
Why is the table not being updated?
There are 3 columns in the table - orderid (which is passed from another table) and then staffid and confirmed which should both be NULL - and are - until the rows are updated. orderid = int not null, staffid = int, confirmed = string.confirm database
The view is a left outer join, meaning that it shows the values that need to be update by the by.
[sql][2]
database diagram
Form
How can this be fixed, its been like this for two days.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.SqlClient;
using System.Data.SqlTypes;
namespace ComicBookShop
{
public partial class orders_confirm : Form
{
public orders_confirm()
{
InitializeComponent();
}
//database details
string connString = "Data Source = BLAH BLAH BLAH";
private void btnBack_Click(object sender, EventArgs e)
{
this.Hide();
ManagmentMain fm = new ManagmentMain();
fm.Show();
}
private void orders_confirm_Load(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(connString);
using (SqlConnection conn = new SqlConnection(connString))
{
using (SqlCommand cmd = new SqlCommand("SELECT * FROM staff_view", con))
{
cmd.CommandType = CommandType.Text;
using (SqlDataAdapter sda = new SqlDataAdapter(cmd))
{
using (DataTable dt = new DataTable())
{
sda.Fill(dt);
//Set AutoGenerateColumns False
dataGridView5.AutoGenerateColumns = true;
dataGridView5.DataSource = dt;
}
}
}
con.Close();
}
}
private void btnUpdate_Click(object sender, EventArgs e)
{
if (txtConfirmed.Text == "" || txtorder.Text == "" || txtstaff.Text == "")
{
MessageBox.Show("Please fill textboxes");
return;
}
//database details
string connString = "Data Source = aak; Initial Catalog = aa; User ID = aa; Password = aa";
SqlConnection con = new SqlConnection(connString);
using (SqlConnection conn = new SqlConnection(connString))
{
using (SqlCommand command = con.CreateCommand())
{
try
{
con.Open();
command.CommandText = "Update dbo.confirm set staffid=#staffid, confirmed=#confirmed where orderid =#orderid";
command.Parameters.AddWithValue("#orderid", txtorder.Text);
command.Parameters.AddWithValue("#staffid", txtstaff.Text);
command.Parameters.AddWithValue("#confirmed", txtConfirmed.Text);
command.ExecuteNonQuery();
con.Close();
MessageBox.Show("Updated");
}
catch (SqlException ex)
{
Console.WriteLine(ex.Message);
}
}
}
}
}
}
this is the part of the code where the data should be inserted
private void btnUpdate_Click(object sender, EventArgs e)
{
if (txtConfirmed.Text == "" || txtorder.Text == "" || txtstaff.Text == "")
{
MessageBox.Show("Please fill textboxes");
return;
}
//database details
string connString = "Data Source = aak; Initial Catalog = aa; User ID = aa; Password = aa";
SqlConnection con = new SqlConnection(connString);
using (SqlConnection conn = new SqlConnection(connString))
{
using (SqlCommand command = con.CreateCommand())
{
try
{
con.Open();
command.CommandText = "Update dbo.confirm set staffid=#staffid, confirmed=#confirmed where orderid =#orderid";
command.Parameters.AddWithValue("#orderid", txtorder.Text);
command.Parameters.AddWithValue("#staffid", txtstaff.Text);
command.Parameters.AddWithValue("#confirmed", txtConfirmed.Text);
command.ExecuteNonQuery();
con.Close();
MessageBox.Show("Updated");
}
catch (SqlException ex)
{
Console.WriteLine(ex.Message);
}
}
}
Try setting parameters with their corresponding data types:
command.Parameters.Add("orderid", SqlDbType.Int);
command.Parameters["orderid"].Value = int.Parse(txtorder.Text);
Do the same for staffid.
I think the issue is you are passing string where int is expected.
I am making a attendance system, and here is my problem now, after i searched for a name of a person and try to log him in for attendance, it is fine at first, after logging in the second name it is still fine. but once i tried to edit the login attendance of the first or second user, all the values in my datagridview(connected to my database) became duplicated. if i enter name1 for attendance in my week1 it is fine. name2 for attendance in week1 is still fine.
but if i edit the same name. or even go to the next week number, all of the saved values got duplicated based on my recent inputed name.
for inserting new records
SqlConnection cnn200 = new SqlConnection(connectionstring);
string sql200 = "SELECT * FROM attendance WHERE csign=#csign ";
cnn200.Open();
SqlCommand cmd200 = new SqlCommand(sql200, cnn200);
SqlDataReader rdr200;
cmd200.Parameters.AddWithValue("#csign", callsign);
rdr200 = cmd200.ExecuteReader();
if (rdr200.Read() == true)
{
SqlConnection cnn201 = new SqlConnection(connectionstring);
if (textBox89.Text == "1")
{
string sql201 = "insert INTO attendance
(csign,name,week1)" + "VALUES" + "(#csign,#name,#week1)";
cnn201.Open();
SqlCommand cmd201 = new SqlCommand(sql201, cnn201);
cmd201.Parameters.AddWithValue("#csign", callsign);
cmd201.Parameters.AddWithValue("#name", namee);
cmd201.Parameters.AddWithValue("#week1",
comboBox1.Text);
cmd201.ExecuteNonQuery();
}
if (textBox89.Text == "2")
{
string sql201 = "insert INTO attendance
(csign,name,week2)" + "VALUES" + "(#csign,#name,#week2)";
cnn201.Open();
SqlCommand cmd201 = new SqlCommand(sql201, cnn201);
cmd201.Parameters.AddWithValue("#csign", callsign);
cmd201.Parameters.AddWithValue("#name", namee);
cmd201.Parameters.AddWithValue("#week2",
comboBox1.Text);
cmd201.ExecuteNonQuery();
}
and for updating
else{
SqlConnection cnn201 = new SqlConnection(connectionstring);
if (textBox89.Text == "1")
{
string sql201 = "UPDATE attendance SET
name=#name,csign=#csign,week1=#week1";
cnn201.Open();
SqlCommand cmd201 = new SqlCommand(sql201, cnn201);
cmd201.Parameters.AddWithValue("#name", namee);
cmd201.Parameters.AddWithValue("#csign", callsign);
cmd201.Parameters.AddWithValue("#week1",
comboBox1.Text);
cmd201.ExecuteNonQuery();
}
if (textBox89.Text == "2")
{
string sql201 = "UPDATE attendance SET
name=#name,csign=#csign,week2=#week2";
cnn201.Open();
SqlCommand cmd201 = new SqlCommand(sql201, cnn201);
cmd201.Parameters.AddWithValue("#name", namee);
cmd201.Parameters.AddWithValue("#csign", callsign);
cmd201.Parameters.AddWithValue("#week2",
comboBox1.Text);
cmd201.ExecuteNonQuery();
}`}
nica, I think I can help. What you are trying to do can be done easily with less coding lines. An entire DataGridView can be displayed, edited, deleted and have no duplicates by using a few more objects
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Windows.Forms;
using System.Globalization;
using System.Data.SqlClient;
using System.IO;
using System.Configuration;
namespace ADO_NET_Testbed
{
public partial class MainForm : Form
{
private SqlDataAdapter adapter;
private string connectionString = #"Data Source=Server;Persist Security Info=True;Password=password!;User ID=sooperuser;Initial Catalog=Database";
private string sqlcommand = #"SELECT OPID, LastName, FirstName, Title, PhoneOffice, PhoneCell, Email, Active, Admin, Tester, Educator, Developer FROM AuditUser";
private SqlCommandBuilder cmdBuilder = new SqlCommandBuilder();
private DataTable datatable = new DataTable();
private DataSet dataset = new DataSet();
public MainForm()
{
InitializeComponent();
}
private void MainForm_Load(object sender, EventArgs e)
{
adapter = new SqlDataAdapter(sqlcommand, connectionString);
adapter.Fill(dataset, "AuditUser");
dgvUsers.DataSource = dataset.Tables[0];
dgvUsers.Enabled = true;
this.Show();
}
private void btnCancel_Click(object sender, EventArgs e)
{
dataset.Clear();
dataset.Reset();
this.Close();
}
private void btnSave_Click(object sender, EventArgs e)
{
cmdBuilder.DataAdapter = adapter;
adapter.Update(dataset.Tables[0]);
this.Close();
}
}
}
As a quick rundown of what is going on, the SqlDataAdapter holds the four queries, but auto-creates three from the SELECT command. Using a SqlCommandBuilder enables the other three to be added, although the debugger will not show them as anything but NULL. The adapter.Fill() and adapter.Update() handle all the different commands based on the RowState of each row in the datagridview. "Cancel" is overkill seeing as this form is closed anyway.
My method is not being called by my application. I've used breakpoints and it's never initiated in the code. I'm building a C# Windows Forms application using an Azure Database, but the DataGridView is never being filled neither is the code being called at all... I have noooo clue whatsoever why..
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.SqlClient;
using System.Configuration;
namespace MyWinFormsProj
{
public partial class CompanyForm : Form
{
public CompanyForm()
{
InitializeComponent();
}
//Connection String
string cs = ConfigurationManager.ConnectionStrings
["MyConnetion"].ConnectionString;
// Load all employees
private void dataEmployees_Load()
{
using (SqlConnection con = new SqlConnection(cs))
{
con.Open();
SqlCommand cmd = new SqlCommand
(
"Select fname,ename FROM dbo.Users", con
);
SqlDataReader dr = cmd.ExecuteReader();
DataTable dt = new DataTable();
dt.Load(dr);
dataEmployees.DataSource = dt;
}
}
// Crate company
private void createCompany_Click_1(object sender, EventArgs e)
{
if (textBoxCompanyName.Text == "")
{
MessageBox.Show("Fill out information");
return;
}
using (SqlConnection con = new SqlConnection(cs))
{
//Create SqlConnection
con.Open();
SqlCommand cmd = new SqlCommand(
"insert into dbo.Company (companyName)
values(#companyName)", con);
cmd.Parameters.AddWithValue(
"#companyName", textBoxCompanyName.Text);
SqlDataAdapter adapt = new SqlDataAdapter(cmd);
MessageBox.Show("Grattis! Du har skapat ett företag");
}
}
}
}
The second method is working and is doing what it is supposed to do, but the first one is never called..
you need to set an event handler on the gridView onLoad and pass this method to the handler
public void GridView_OnLoad(object sender, EventArgs e)
{
dataEmployees_Load();
}
You need to fix your method signature to look like this:
private void dataEmployees_Load(object sender, EventArgs e)
Then, in your GirdView, you need to set this function as handler for event "onload":
OnLoad="dataEmployees_Load"
Thank you guys for your answers it helped my solve the problem. Like you were saying the problem was in the method not being called. So I called it directly on initiliazeComponent like this.
public partial class CompanyForm : Form
{
public CompanyForm()
{
InitializeComponent();
Load += new EventHandler(dataEmployees_Load); //Added this code
}
// Load all employees
private void dataEmployees_Load(object sender, EventArgs e)
{
using (SqlConnection con = new SqlConnection(cs))
{
con.Open();
SqlCommand cmd = new SqlCommand
(
"Select fname,ename FROM dbo.Users", con
);
SqlDataReader dr = cmd.ExecuteReader();
DataTable dt = new DataTable();
dt.Load(dr);
dataEmployees.DataSource = dt;
}
}
i have a slight problem here,I have the following master tables
M_employee
EMPID Name
1 abc
2 xyz
M_Division
DIVID EMPID DIVISON
1 2 arts
2 1 science
M_Designation
DESGID EMPID Designation
1 2 Teacher
2 1 Scientist
and based on the ID's present in the master table i retrieve few fields on a label in a form....What i want to do is when i store these values of the form in a new table i want only the id's to be stored and not the text values which are being displayed in the label of the form.Below is the code I tried..Can anyone help me?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Data;
using System.Data.OleDb;
using System.Configuration;
using System.Web.UI.HtmlControls;
using System.Xml.Linq;
namespace Travel1.Forms
{
public partial class temporaryduty : System.Web.UI.Page
{
SqlConnection conn = new SqlConnection("Server; Database; Integrated security = true");
protected void Page_Load(object sender, EventArgs e)
{
Lbltoday.Text = DateTime.Now.ToString();
if (!IsPostBack)
{
GetName();//adding the group to the dropdownbox
}
}
private void GetName()
{
SqlCommand cmd = new SqlCommand("Select EMPID,Name FROM M_employee where IsActive=1 ORDER BY Name", conn);
DataSet objDs = new DataSet();
SqlDataAdapter sd = new SqlDataAdapter(cmd);
conn.Open();
sd.Fill(objDs);
conn.Close();
if (objDs.Tables[0].Rows.Count > 0)
{
ddlname.DataSource = objDs.Tables[0];
ddlname.DataTextField = "Name";
ddlname.DataValueField = "EMPID";
ddlname.DataBind();
ddlname.Items.Insert(0, "--Select--");
}
}
protected void ddlname_SelectedIndexChanged(object sender, EventArgs e)
{
GetDivision(ddlname.SelectedItem.Value);
}
private void GetDivision(string Name)
{
SqlCommand cmd = new SqlCommand("SELECT M_employee.Name, M_Division.DIVISION, M_Division.DIVID AS Expr1, M_Designation.DesigID AS Expr2, M_Designation.Designation FROM M_employee INNER JOIN M_Division ON M_employee.DIVID = M_Division.DIVID INNER JOIN M_Designation ON M_employee.DesigID = M_Designation.DesigID WHERE M_employee.EMPID=#EMPID ", conn);
cmd.Parameters.AddWithValue("#EMPID", Name);
DataSet objDs = new DataSet();
SqlDataAdapter sd = new SqlDataAdapter(cmd);
conn.Open();
sd.Fill(objDs);
conn.Close();
if (objDs.Tables[0].Rows.Count > 0)
{
lbldiv.Text = objDs.Tables[0].Rows[0]["DIVISION"].ToString();
lbldesig.Text = objDs.Tables[0].Rows[0]["Designation"].ToString();
}
}
protected void btnSubmit_Click2(object sender, EventArgs e)
{
string RelaseDate = Calendar1.SelectedDate.Date.ToString();
SqlCommand cmd = new SqlCommand("Insert into T_TADA_tempform(EMPID,DIVID,DesigID) values(#EMPID,#DIVID,#DesigID)", conn);
cmd.Parameters.AddWithValue("#EMPID", ddlname.SelectedValue);
cmd.Parameters.AddWithValue("#DIVID", lbldesig.Text);
cmd.Parameters.AddWithValue("#DesigID", lbldiv.Text);
if (conn.State == ConnectionState.Closed)
{
conn.Open();
int cnt = cmd.ExecuteNonQuery();
conn.Close();
if (cnt == 1)
{
Response.Redirect("form.aspx");
}
else
Response.Write("Form has not been submitted,Please Try again!");
}
}
}
}
As requested, here is the idiomatic way of using using for IDisposable resources. Note, I've done nothing else with the code's logic but that, so pay attention to other answers :)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Data;
using System.Data.OleDb;
using System.Configuration;
using System.Web.UI.HtmlControls;
using System.Xml.Linq;
namespace Travel1.Forms
{
public partial class temporaryduty : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
Lbltoday.Text = DateTime.Now.ToString();
if (!IsPostBack)
{
GetName();//adding the group to the dropdownbox
}
}
private void GetName()
{
using (SqlConnection conn = new SqlConnection("Server; Database; Integrated security = true"))
using (SqlCommand cmd = new SqlCommand("Select EMPID,Name FROM M_employee where IsActive=1 ORDER BY Name", conn))
using (DataSet objDs = new DataSet())
using (SqlDataAdapter sd = new SqlDataAdapter(cmd))
{
conn.Open();
sd.Fill(objDs);
if (objDs.Tables[0].Rows.Count > 0)
{
ddlname.DataSource = objDs.Tables[0];
ddlname.DataTextField = "Name";
ddlname.DataValueField = "EMPID";
ddlname.DataBind();
ddlname.Items.Insert(0, "--Select--");
}
}
}
protected void ddlname_SelectedIndexChanged(object sender, EventArgs e)
{
GetDivision(ddlname.SelectedItem.Value);
}
private void GetDivision(string Name)
{
using (SqlConnection conn = new SqlConnection("Server; Database; Integrated security = true"))
using (SqlCommand cmd = new SqlCommand("SELECT M_employee.Name, M_Division.DIVISION, M_Division.DIVID AS Expr1, M_Designation.DesigID AS Expr2, M_Designation.Designation FROM M_employee INNER JOIN M_Division ON M_employee.DIVID = M_Division.DIVID INNER JOIN M_Designation ON M_employee.DesigID = M_Designation.DesigID WHERE M_employee.EMPID=#EMPID ", conn))
using (DataSet objDs = new DataSet())
using (SqlDataAdapter sd = new SqlDataAdapter(cmd))
{
cmd.Parameters.AddWithValue("#EMPID", Name);
conn.Open();
sd.Fill(objDs);
if (objDs.Tables[0].Rows.Count > 0)
{
lbldiv.Text = objDs.Tables[0].Rows[0]["DIVISION"].ToString();
lbldesig.Text = objDs.Tables[0].Rows[0]["Designation"].ToString();
}
}
}
protected void btnSubmit_Click2(object sender, EventArgs e)
{
string RelaseDate = Calendar1.SelectedDate.Date.ToString();
int cnt;
using (SqlConnection conn = new SqlConnection("Server; Database; Integrated security = true"))
using (SqlCommand cmd = new SqlCommand("Insert into T_TADA_tempform(EMPID,DIVID,DesigID) values(#EMPID,#DIVID,#DesigID)", conn))
{
cmd.Parameters.AddWithValue("#EMPID", ddlname.SelectedValue);
cmd.Parameters.AddWithValue("#DIVID", lbldesig.Text);
cmd.Parameters.AddWithValue("#DesigID", lbldiv.Text);
conn.Open();
cnt = cmd.ExecuteNonQuery();
}
if (cnt == 1)
{
Response.Redirect("form.aspx");
}
else
Response.Write("Form has not been submitted,Please Try again!");
}
}
}
When you read in your division and designation, store the ids somewhere, like in a private filed of this class:
public partial class temporaryduty : System.Web.UI.Page
{
private int divisionId;
private int designationId;
...
if (objDs.Tables[0].Rows.Count > 0)
{
lbldiv.Text = objDs.Tables[0].Rows[0]["DIVISION"].ToString();
lbldesig.Text = objDs.Tables[0].Rows[0]["Designation"].ToString();
divisionId = objDs.Tables[0].Rows[0]["Expr1"];
designationId = objDs.Tables[0].Rows[0]["Expr2"];
}
Then, on your button click use those fields to insert the ids:
cmd.Parameters.AddWithValue("#DIVID", divisionId);
cmd.Parameters.AddWithValue("#DesigID", designationId);
My problem is that I can't print out all the data from the table in my mysql database, I got out just last row in the given table "teacher". is there anyone who can help me find the error?
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using MySql.Data.MySqlClient;
namespace ReadDataFromMysql
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
string sql = " SELECT * FROM teacher ";
MySqlConnection con = new MySqlConnection("host=localhost;user=root;password=859694;database=projekt;");
MySqlCommand cmd = new MySqlCommand(sql, con);
con.Open();
MySqlDataReader reader = cmd.ExecuteReader();
while (reader.Read()) {
data2txt.Text = reader.GetString("id");
datatxt.Text = reader.GetString("userId");
}
}
private void btnclose_Click(object sender, EventArgs e)
{
Close();
}
}
}
Your problem is that you are overwriting data2txt.Text and datatxt.Text on each row of data. if you want to see all of the data in those fields, something like this should do what you need:
data2txt.Text = string.Empty;
datatxt.Text = string.Empty;
while (reader.Read())
{
data2txt.Text += $"{reader.GetString("id")};";
datatxt.Text += $"{reader.GetString("userId")};";
}
You're assigning the value of each field instead of the value of the existing control's text plus the new value. Add a breakpoint to make sure you're getting multiple rows, but as your code is written, you would only see the result of one row in your form because you're overwriting on each iteration through the loop.
This code works.
private void getdata()
{
MySqlConnection connect = new MySqlConnection("SERVER=localhost; user id=root; password=; database=databasename");
MySqlCommand cmd = new MySqlCommand("SELECT ID, name FROM data WHERE ID='" + txtid.Text + "'");
cmd.CommandType = CommandType.Text;
cmd.Connection = connect;
connect.Open();
try
{
MySqlDataReader dr;
dr = cmd.ExecuteReader();
while(dr.Read())
{
txtID.Text = dr.GetString("ID");
txtname.Text = dr.GetString("name");
}
dr.Close();
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
if(connect.State == ConnectionState.Open)
{
connect.Close();
}
}
Obviously your code shows the last row values of teacher table into your text fields on form.Because your are looping throught the datareader and assigning the values to textfiled.So each iteration it will overwright the previous values in textbox.
You should output the data before again writing in it:
data2txt.Text = reader.GetString("id");
datatxt.Text = reader.GetString("userId");
Or use a var to store all the data in with each 'read' and then output that var
varexample.Text += reader.GetString("id");