Reading Data from SQL DataBase Table to generic collection - c#

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);
}

Related

SQL DataReader: Invalid attempt to read when no data is present to label

I am trying to use a SqlDataReader to run queries on two tables where the 1st column in the Selection table is a foreign key referencing to the Items table, and then display the results in labels, but I keep getting the error:
Invalid attempt to read when no data is present.
Here is my code:
public partial class Read : System.Web.UI.Page
{
SqlConnection conn = new SqlConnection(#"data source = localhost; integrated security = true; database = dev_handin1");
SqlCommand cmd = null;
SqlDataReader rdr = null;
string sqlsel = "SELECT MainItemId FROM Selection";
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
GetInfo();
}
}
private void GetInfo() {
try
{
cmd = new SqlCommand(sqlsel, conn);
conn.Open();
sqlsel = "SELECT * FROM Items WHERE ItemId = MyMainItem";
rdr = cmd.ExecuteReader();
var MyMainItem = rdr[0];
while (rdr.Read())
{
LabelCategory1.Text = rdr[1].ToString();
LabelHeadline1.Text = rdr[2].ToString();
LabelText1.Text = rdr[3].ToString();
LabelJoke1.Text = rdr[4].ToString();
}
}
catch (Exception ex)
{
LabelMessage1.Text = ex.Message;
}
finally
{
rdr.Close();
conn.Close();
}
}
}
}
I'm pretty new at this so please bear with me.

How to fix code to return full list instead of one row from SqlDataReader in C# Web API

I am building a web API that connects to SQL and am trying to return all rows from the db in which the "StartDateTime" value is equal to today's date. For some reason, I am only getting one row instead of all rows that fit the definition. What do I need to change?
public class EventsController : ApiController
{
public List<tblEventDate> Get()
{
using (CalendarEntities entities = new CalendarEntities())
{
tblEventDate singleEvent = new tblEventDate();
List<tblEventDate> eventList = new List<tblEventDate>();
string strcon = ConfigurationManager.ConnectionStrings["DbConnCalendar"].ConnectionString;
SqlConnection con = new SqlConnection(strcon);
con.Open();
string comm = "SELECT [dbo].[tblEventDates].[EventID], [dbo].[tblEventDates].[StartDateTime], WHERE (CONVERT(date, dbo.tblEventDates.StartDateTime) = CONVERT(date, GETDATE()))";
SqlCommand cmd = new SqlCommand(comm, con);
using (SqlDataReader reader = cmd.ExecuteReader())
{
while (reader.HasRows)
{
while (reader.Read())
{
singleEvent.StartDateTime = (DateTime)(reader["StartDateTime"]);
singleEvent.EventID = (long)reader["EventID"];
eventList.Add(singleEvent);
}
reader.NextResult();
}
con.Close();
}
return eventList;
}
}
}
Try this:
conn.Open();
SqlDataReader reader = cmd.ExecuteReader(CommandBehavior.CloseConnection);
while (reader.Read())
{
if (reader.HasRows)
{
singleEvent.StartDateTime = (DateTime)(reader["StartDateTime"]);
singleEvent.EventID = (long)reader["EventID"];
eventList.Add(singleEvent);
}
}

Fill public strings with Database info from userlogin

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;

SQLDataReader bugging while using .Nest() or .Read()

I'm retrieving some information from an MSSQL via SQLDataReader, but while debugging it I notice in some cases the reader clears the result view with the error "Enumeration yielded no results" see the screenshot Before Running passing Read(),
After passing read()
this is my code,the error happens on getActiveUsers() method.
getDatabases() works just fine. could someone help me? cheers
public partial class automation : System.Web.UI.Page
{
SqlConnection con;
static List<ActiveUsers> activeUsers = new List<ActiveUsers>();
protected void Page_Load(object sender, EventArgs e)
{
ASPxGridView1.DataSource = activeUsers.ToList();
}
public List<ActiveUsers> getDatabases()
{
//passing query
string SqlQuery = "SELECT [WorkspaceName],[MaConfig_Customers].Name FROM [MaConfig_CustomerDatabases] INNER JOIN [MaConfig_Customers] ON [MaConfig_CustomerDatabases].CustomerId = [MaConfig_Customers].CustomerId where [MaConfig_Customers].Status = 0";
//creating connection
string sqlconn = ConfigurationManager.ConnectionStrings["MaxLiveConnectionString"].ConnectionString;
con = new System.Data.SqlClient.SqlConnection(sqlconn);
var cmd = new SqlCommand(SqlQuery, con);
con.Open();
SqlDataReader reader = cmd.ExecuteReader();
List<ActiveUsers> results = new List<ActiveUsers>();
if (reader.Read())
{
while (reader.Read())
{
ActiveUsers company = new ActiveUsers();
company.DatabaseName = String.Format("{0}", reader["WorkspaceName"]);
company.ClientName = String.Format("{0}", reader["Name"]);
results.Add(company);
}
}
con.Close();
return results;
}
public void getActiveUsers()
{
activeUsers.Clear();
List<ActiveUsers> Databases= getDatabases();
SqlConnection conn = new SqlConnection();
string SqlQuery = "select [disabled], [ADMN_Users1].[Record_Id] ,[ADMN_Users].[User_Id] from admn_Users1 inner join [ADMN_Users] on [ADMN_Users1].[record_Id] = [ADMN_Users].[Record_Id] Where [disabled] & 0x2 = 0 ";
for (int i = 0;i < Databases.Count;i++)
{
conn.ConnectionString =
"Data Source=MAXSQLCLUS01;" +
"Initial Catalog=" + Databases[i].ToString()+";"+
"User id=sa;" +
"Password=Max1m1zer;";
var cmd = new SqlCommand(SqlQuery, conn);
conn.Open();
SqlDataReader reader = cmd.ExecuteReader();
int NumberOfUsersCounter = 0 ;
//TODO Select Enabled users
if (reader.Read())
{
while (reader.Read())
{
string user = String.Format("{0}", reader["User_Id"]);
//logic to remove system users
if (user.Equals("master", StringComparison.CurrentCultureIgnoreCase))
{
}
else
if (user.Equals("emailuser", StringComparison.CurrentCultureIgnoreCase))
{
}
else
if (user.Equals("webuser", StringComparison.CurrentCultureIgnoreCase))
{
}
else
{
NumberOfUsersCounter++;
}
}
ActiveUsers newEntry = new ActiveUsers();
newEntry.NumberActiveUsers = NumberOfUsersCounter.ToString();
newEntry.DatabaseName = Databases[i].DatabaseName.ToString();
newEntry.ClientName = Databases[i].ClientName.ToString();
activeUsers.Add(newEntry);
}
conn.Close();
//Add to ActiveUsers list
}
ASPxGridView1.AutoGenerateColumns = true;
ASPxGridView1.DataSource = activeUsers.ToList();
ASPxGridView1.DataBind();
}
protected void ASPxButton1_Click(object sender, EventArgs e)
{
getActiveUsers();
}
protected void btnExportExcel_Click(object sender, EventArgs e)
{
ASPxGridView1.DataBind();
ASPxGridViewExporter1.Landscape = true;
ASPxGridViewExporter1.FileName = "User Count Report";
ASPxGridViewExporter1.WriteXlsToResponse();
}
}
}
if (reader.Read())
{
while (reader.Read())
{
ActiveUsers company = new ActiveUsers();
company.DatabaseName = String.Format("{0}", reader["WorkspaceName"]);
company.ClientName = String.Format("{0}", reader["Name"]);
results.Add(company);
}
}
use this
if (reader.HasRows)
{
while (reader.Read())
{
ActiveUsers company = new ActiveUsers();
company.DatabaseName = String.Format("{0}", reader["WorkspaceName"]);
company.ClientName = String.Format("{0}", reader["Name"]);
results.Add(company);
}
}
your if Condition is wrong
if(reader.Read()) ==> is Wrong
Read() is not return boolean Value
use HasRows to check rows in SQLDataReader
You are skipping the first result. if (reader.Read()) { while(reader.Read()) {.... Remove the enclosing if, all it does is see if there is a row and retrieve it but then you do not read it, instead you do it again in the if so the first result is always discarded.
public List<ActiveUsers> getDatabases()
{
//passing query
string SqlQuery = "SELECT [WorkspaceName],[MaConfig_Customers].Name FROM [MaConfig_CustomerDatabases] INNER JOIN [MaConfig_Customers] ON [MaConfig_CustomerDatabases].CustomerId = [MaConfig_Customers].CustomerId where [MaConfig_Customers].Status = 0";
//creating connection
string sqlconn = ConfigurationManager.ConnectionStrings["MaxLiveConnectionString"].ConnectionString;
using(con = new System.Data.SqlClient.SqlConnection(sqlconn))
using(var cmd = new SqlCommand(SqlQuery, con))
{
con.Open();
using(SqlDataReader reader = cmd.ExecuteReader())
{
List<ActiveUsers> results = new List<ActiveUsers>();
while (reader.Read())
{
ActiveUsers company = new ActiveUsers();
company.DatabaseName = reader.GetString(0);
company.ClientName = reader.GetString(1);
results.Add(company);
}
}
}
return results;
}
Side notes:
company.DatabaseName = String.Format("{0}", reader["WorkspaceName"]) would be better written as company.DatabaseName = reader.GetString(0). The same goes for the next line. No need to use string.Format and you are specifying the columns and order in the query so use the ordinal index so get the native value.
I would recommend you wrap the SqlConnection and SqlDataReader in using blocks to ensure they are closed/disposed after use even in the event of an exception.

Display the generic list items in the labels

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.

Categories