I just want to display the student details from the generic list in the labels which is in the design.
I'm getting the error in the foreach loop that x is not in the current context.
namespace gentask
{
public partial class WebForm2 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection();
conn.ConnectionString = #"Data Source=Sadiq;Initial Catalog=rafi;Integrated Security=True";
conn.Open();
SqlCommand cmd = new SqlCommand();
cmd.Connection = conn;
cmd.CommandText = "select * from student";
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
}
}
public class student
{
student std;
List<student> stud = new List<student>();
public void load()
{
foreach (DataRow dr in x)
{
std = new stud();
std.id = x[0].Tostring();
std.name = x[1].Tostring();
std.age = x[2].Tostring();
std.school = x[3].Tostring();
std.clas = x[4].Tostring();
std.marks = x[5].Tostring();
std.grade = x[6].Tostring();
stud.Add(std);
}
}
public void show()
{
foreach (student std in stud)
{
std.id = label.text;
std.name = label1.text;
std.age = label2.text;
std.school = label3.text;
std.clas = label4.text;
std.marks = label5.text;
std.grade = Label6.Text;
}
}
}
}
The error message seems pretty clear - you are trying to iterate over x which is not defined anywhere that the method can access:
foreach (DataRow dr in x) // what is x?
You also have these problems :
You are trying to reference all of the textboxes from the form in Student.Show().
You are trying to create an instance of stud that is not defined anywhere that I can see:
std = new stud();
You are trying to add the "stud" to a List of Students (I'm assuming that stud does not inherit from Student.
Related
I am trying to make it so that when changing the value in the comboBox, the database is displayed in the dataGridview. Everything seems to work, but when you close the form it gives an error:
enter image:
Code:
namespace Cursach
{
public partial class VoucherForm : Form
{
public VoucherForm()
{
InitializeComponent();
}
public void VoucherCountry()
{
dataGridView1.AllowUserToAddRows = false;
dataGridView1.AllowUserToDeleteRows = false;
dataGridView1.AllowUserToOrderColumns = false;
dataGridView1.AllowUserToResizeRows = false;
dataGridView1.AllowDrop = false;
dataGridView1.ReadOnly = true;
DB dB = new DB();
SqlCommand command = new SqlCommand("SELECT * FROM Voucher WHERE Name_Country= #nC", dB.ConnectionSQL());
command.Parameters.Add("#nC", SqlDbType.VarChar).Value = comboBox1.SelectedValue;
DataTable table = new DataTable();
SqlDataAdapter adapter = new SqlDataAdapter();
dB.OpenSQL();
adapter.SelectCommand = command;
adapter.Fill(table);
dataGridView1.DataSource = table;
dB.ClodeSQL();
}
private void VoucherForm_Load(object sender, EventArgs e)
{
this.countryTableAdapter.Fill(this.cursacDat.Country);
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
VoucherCountry();
}
}
You have a DB class which is good to separate you database code from your user interface code. I moved the database code to retrieve the Country data to the DB class. Notice how the DB class knows nothing about the user interface and the user interface knows nothing about the database.
Database objects need to be closed and disposed. using blocks take care of this for you even if there is an error.
public class DB
{
private string ConStr = "Your connection string";
public DataTable GetCountryData(string nC)
{
DataTable dt = new DataTable();
using (SqlConnection cn = new SqlConnection(ConStr))
using (SqlCommand cmd = new SqlCommand("SELECT * FROM Voucher WHERE Name_Country= #nC", cn))
{
cmd.Parameters.Add("#nC", SqlDbType.VarChar, 100).Value = nC;
cn.Open();
dt.Load(cmd.ExecuteReader());
}
return dt;
}
}
Then in the form.
private void OpCode()
{
if (comboBox1.SelectedIndex < 0)
{
MessageBox.Show("Please select a value in the drop down.");
return;
}
DB DataClass = new DB();
dataGridView1.DataSource = DataClass.GetCountryData(comboBox1.SelectedValue.ToString());
}
i'm trying to get multiple values from database in return, i write a code and it return me only one value but i want all values in return. i didn't know how to solve it because i'm beginner in c#. here is code
string CommandText = "SELECT * FROM SV WHERE [SVCode]=#id";
using (SQLiteCommand cmd = new SQLiteCommand(CommandText, conn))
{
cmd.Parameters.AddWithValue("#id", sve.SVID);
conn.Open();
DataTable dt = new DataTable();
SQLiteDataAdapter da = new SQLiteDataAdapter(cmd);
da.Fill(dt);
foreach (DataRow dr in dt.Rows)
{
sve.SVName = dr["SVName"].ToString();
sve.SVCity = dr["SVCity"].ToString();
sve.SVState = dr["SVState"].ToString();
sve.SVEmail = dr["SVEmail"].ToString();
sve.SVWebsite = dr["SVWebsite"].ToString();
sve.SVAddress = dr["SVAddress"].ToString();
sve.SVNote = dr["SVNote"].ToString();
}
return sve.SVName; //how to return SVCity,SVState,SVEmail,SVWebsite,SVAddress,SVNote
}
private string SVCB(){
SVE sve = new SVE();
sve.SVID = MSVD_vendorcode.SelectedItem.ToString();
sve.SVName = MSVD_vendorname.Text;
sve.SVCity = MSVD_vendorcity.Text;
sve.SVState = MSVD_vendorstate.Text;
sve.SVEmail = MSVD_vendoremail.Text;
sve.SVWebsite = MSVD_vendorwebsite.Text;
sve.SVAddress = MSVD_vendoraddress.Text;
sve.SVNote = MSVD_vendornote.Text;
SVSCB sv = new SVSCB();
return sv.SVCBSI(sve);}
private void SVcode_SelectedIndexChanged(object sender, EventArgs e)
{
MSVname.Text = SVCB();
MSVcity.Text = SVCB();
MSVstate.Text = SVCB();
MSVemail.Text = SVCB();
MSVwebsite.Text = SVCB();
MSVaddress.Text = SVCB();
MSVnote.Text = SVCB();
}
this code working but show only one value of SVName in every textbox.
Update!!
public static string SV_CBSI(SVE sve)
{
using (SQLiteConnection conn = new SQLiteConnection(DatabaseConnection.ConnectionString()))
{
string CommandText = "SELECT * FROM SV WHERE [SVCode]=#id";
using (SQLiteCommand cmd = new SQLiteCommand(CommandText, conn))
{
cmd.Parameters.AddWithValue("#id", sve.SVID);
conn.Open();
DataTable dt = new DataTable();
SQLiteDataAdapter da = new SQLiteDataAdapter(cmd);
da.Fill(dt);
foreach (DataRow dr in dt.Rows)
{
sve.SVName = dr["SVName"].ToString();
sve.SVCity = dr["SVCity"].ToString();
sve.SVState = dr["SVState"].ToString();
sve.SVEmail = dr["SVEmail"].ToString();
sve.SVWebsite = dr["SVWebsite"].ToString();
sve.SVAddress = dr["SVAddress"].ToString();
sve.SVNote = dr["SVNote"].ToString();
}
return sve.SVName; //how to return SVCity,SVState,SVEmail,SVWebsite,SVAddress,SVNote
}
}
}
public static string SVCBSI(SVE sve)
{
return SVWCB.SV_CBSI(sve);
}
here is complete code
You need to have a method that return the whole SVE retrieved from database given a particular SVCode.
Notice that I suppose that SVCode is an integer. If not change the input type for this method accordingly
public SVE SV_CBSI(int id)
{
SVE localSve = new SVE();
string CommandText = "SELECT * FROM SV WHERE [SVCode]=#id";
using (SQLiteCommand cmd = new SQLiteCommand(CommandText, conn))
{
cmd.Parameters.AddWithValue("#id", id);
conn.Open();
DataTable dt = new DataTable();
SQLiteDataAdapter da = new SQLiteDataAdapter(cmd);
da.Fill(dt);
if(dt.Rows.Count > 0)
{
localSve.SVName = dr["SVName"].ToString();
localSve.SVCity = dr["SVCity"].ToString();
localSve.SVState = dr["SVState"].ToString();
localSve.SVEmail = dr["SVEmail"].ToString();
localSve.SVWebsite = dr["SVWebsite"].ToString();
localSve.SVAddress = dr["SVAddress"].ToString();
localSve.SVNote = dr["SVNote"].ToString();
}
return localSve;
}
}
Now you can call this method and get back the reference to an SVE instance filled with your data.
private void SVcode_SelectedIndexChanged(object sender, EventArgs e)
{
SVE currentSVE = SV_CBSI(Convert.ToInt32(SVCode.SelectedItem))
MSVname.Text = currentSVE.SVName;
MSVcity.Text = currentSVE.SVCity;
MSVstate.Text = currentSVE.State;
MSVemail.Text = currentSVE.SVEmail;
MSVwebsite.Text = currentSVE.SVWebsite;
MSVaddress.Text = currentSVE.SVAddress;
MSVnote.Text = currentSVE.SVNote;
}
May be you need to return an array (or a List) of strings?
I have created a class that gets the user details from DB to strings (username,userpassword,usernr,usersubco).
What i want to happen is that those strings fill with the info from the user I login with.
public class Details
{
public connectionUser constring = new connectionUser();
public string Technr;
public string Techpass;
public string Techname;
public string Techsubco;
public Details()
{
using (SqlConnection con = new SqlConnection(constring.source))
{
myInlogForm myI = new myInlogForm();
con.Open();
SqlCommand cmd = new SqlCommand("select * from techs where technr=#technr", con);
cmd.Parameters.Add(#"technr", SqlDbType.Int).Value = myI.technr;
cmd.ExecuteNonQuery();
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
Technr = reader[0].ToString();
Techpass = reader[1].ToString();
Techname = reader[2].ToString();
Techsubco = reader[3].ToString();
break;
}
con.Close();
}
MessageBox.Show(Techname + Technr + Techpass + Techsubco);
}
myI = usercontrol (inlogscreen)
myIn.technummer is a public string that get value on loginbutton from textbox.
when I push login I got the message box from this class above (empty) and following error :
UPDATED !!!
System.Data.SqlClient.SqlException: 'The parameterized query
'(#technr int)select * from techs where technr=#technr' expects the
parameter '#technr', which was not supplied.'
public event EventHandler<EventArgs> callMenu; // oproep door mainform
public event EventHandler<EventArgs> callDash; // oproep door mainform
public int technr;
private void loginBtn_Click(object sender, EventArgs e)
{
using (SqlConnection con = new SqlConnection(cUser.source.ToString()))
{
con.Open();
SqlCommand cmd = new SqlCommand("select technr,techcode from techs where technr=#technr and techcode=#techcode", con);
cmd.Parameters.Add(#"technr",SqlDbType.Int).Value = userTxb.Text;
cmd.Parameters.Add(#"techcode",SqlDbType.VarChar).Value = passTxb.Text;
cmd.ExecuteNonQuery();
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
if (dt.Rows.Count > 0 && callMenu != null && callDash != null) // checks login is juist
{
callMenu(this, new EventArgs());
callDash(this, new EventArgs());
technr = int.Parse(userTxb.Text);
}
else
{
MessageBox.Show("Foutieve gegevens");
}
con.Close();
}
}
try it in this way
cmd.Parameters.Add(#"#technr", SqlDbType.Int).Value = myI.technr;
Hi im new to programming and currently working on a project that lets a user enter its
registration data into a local database using textBoxes. The code works that its adding the items into the database
and after i press a "Show_users" button it displays them in the listBox_users listbox.
My problem is that when i choose a name from the listBox_users it should dislay the data about the selected user in the upper textBox'es i used to enter
the data in the first place using the event i created for the listBox_users,
but im getting an error that "can't read data from database that is already closed".
namespace Userform
{
public partial class Form1: Form
{
SqlCeDataReader rdr;
public Form1()
{
InitializeComponent();
}
// Some code between...
private void button_ShowUsers_Click(object sender, EventArgs e) //code that shows users in listBox
{
var dt = new DataTable();
string connectionString2 = #"Data Source=MyDatabase;Password=xxxxxx;";
using (var cn = new SqlCeConnection(connectionString2))
using (var cmd = new SqlCeCommand("Select * From Users", cn))
{
cn.Open();
using (var reader = cmd.ExecuteReader())
{
dt.Load(reader);
var results = (from row in dt.AsEnumerable()
select new
{
//UserID = row.Field<int>("ID"),
FirstName = row.Field<string>("Firsname"),
LastName = row.Field<string>("Lastname"),
FullName = row.Field<string>("Firstname") + " " + row.Field<string>("Lastname")
}).ToList();
listBox_users.DataSource = results;
listBox_users.DisplayMember = "FullName";
rdr = cmd.ExecuteReader();
}
}
}
//I made an event for the listBox_users:
private void listBox_users_SelectedIndexChanged(object sender, EventArgs e)
//event code that should show listbox selected data in the textBoxes
{
if (listBox_inimesed.SelectedItem != null && rdr != null)
{
try
{
if (rdr.Read())
{
textBox1_firstname.Text = rdr.GetString(1);
textBox2_lastname.Text = rdr.GetString(2);
textBox3_email.Text = rdr.GetString(3);
textBox4_address.Text = rdr.GetString(4);
dateTimePicker1.Value = rdr.GetDateTime(5);
richTextBox_info.Text = rdr.GetString(6);
}
else MessageBox.Show("Object not found");
}
finally
{
rdr.Close();
}
}
}
}
The connection that the reader you are using is dependent on has been closed in the button_ShowUsers_Click event.
It is not a good practice to try to share connections and DataReaders across events. That will result in open connections that are not disposed of correctly. A better practice would be to have the creation of the Connection, Command, and DataReader take place in each event method. By using the "using" statement they will be closed and disposed of correctly in each method. You can also remove the class level variable "rdr".
namespace Userform
{
public partial class Form1 : Form
{
const string connectionString2 = #"Data Source=MyDatabase;Password=xxxxxx;";
public Form1()
{
InitializeComponent();
}
// Some code between...
private void button_ShowUsers_Click(object sender, EventArgs e) //code that shows users in listBox
{
var dt = new DataTable();
using (var cn = new SqlCeConnection(connectionString2))
using (var cmd = new SqlCeCommand("Select * From Users", cn))
{
cn.Open();
using (var reader = cmd.ExecuteReader())
{
dt.Load(reader);
var results = (from row in dt.AsEnumerable()
select new
{
//UserID = row.Field<int>("ID"),
FirstName = row.Field<string>("Firsname"),
LastName = row.Field<string>("Lastname"),
FullName = row.Field<string>("Firstname") + " " + row.Field<string>("Lastname")
}).ToList();
listBox_users.DataSource = results;
listBox_users.DisplayMember = "FullName";
}
}
}
//I made an event for the listBox_users:
private void listBox_users_SelectedIndexChanged(object sender, EventArgs e)
//event code that should show listbox selected data in the textBoxes
{
if (listBox_inimesed.SelectedItem != null)
{
using (var cn = new SqlCeConnection(connectionString2))
using (var cmd = new SqlCeCommand("Select * From Users", cn))
{
cn.Open();
using (var reader = cmd.ExecuteReader())
{
if (reader.Read())
{
textBox1_firstname.Text = reader.GetString(1);
textBox2_lastname.Text = reader.GetString(2);
textBox3_email.Text = reader.GetString(3);
textBox4_address.Text = reader.GetString(4);
dateTimePicker1.Value = reader.GetDateTime(5);
richTextBox_info.Text = reader.GetString(6);
}
else MessageBox.Show("Object not found");
}
}
}
}
}
}
I wanted to read all data from a table(containg 3 rows) and to add all the data into generic collection.From collection i wana bind to gridview.
The code displayed below works but only last row is displayed 3 times in gridview.Can You help me.Am a beginer
protected void Page_Load(object sender, EventArgs e)
{
List<Student> listid = new List<Student>();
Student stud = new Student();
SqlConnection con = new SqlConnection("........");
string sql = "select * from StudentInfo";
con.Open();
SqlCommand cmd = new SqlCommand(sql, con);
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
stud.Studid = Convert.ToInt32(dr["StudId"]);
stud.StudName = dr["StudName"].ToString();
stud.StudentDept = dr["StudentDept"].ToString();
listid.Add(stud);
}
GridView1.DataSource = listid;
GridView1.DataBind();
}
public class Student
{
private int studid;
public int Studid
{
get { return studid; }
set { studid = value; }
}
private string studName;
public string StudName
{
get { return studName; }
set { studName = value; }
}
private string studentDept;
public string StudentDept
{
get { return studentDept; }
set { studentDept = value; }
}
The output is like this:
You need to instantiate your object inside while loop
Otherwise you will have same data in the collection
So the code should be
protected void Page_Load(object sender, EventArgs e)
{
List<Student> listid = new List<Student>();
SqlConnection con = new SqlConnection("........");
string sql = "select * from StudentInfo";
con.Open();
SqlCommand cmd = new SqlCommand(sql, con);
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
Student stud = new Student();
stud.Studid = Convert.ToInt32(dr["StudId"]);
stud.StudName = dr["StudName"].ToString();
stud.StudentDept = dr["StudentDept"].ToString();
listid.Add(stud);
}
GridView1.DataSource = listid;
GridView1.DataBind();
}
Also it is not a good practice to use while to data reader or directly open connection
You should use using statement.
using(SqlConnection con = new SqlConnection("connection string"))
{
con.Open();
using(SqlCommand cmd = new SqlCommand("SELECT * FROM SomeTable", connection))
{
using (SqlDataReader reader = cmd.ExecuteReader())
{
if (reader != null)
{
while (reader.Read())
{
//do something
}
}
} // reader closed and disposed up here
} // command disposed here
} //connection closed and disposed here
In the DataReader while loop instantiate a new Student for each row in the database table:
while (dr.Read())
{
var stud = new Student();
stud.Studid = Convert.ToInt32(dr["StudId"]);
stud.StudName = dr["StudName"].ToString();
stud.StudentDept = dr["StudentDept"].ToString();
listid.Add(stud);
}