Home > front end >  C# - SqlDataReader missing columns
C# - SqlDataReader missing columns

Time:04-19

Here is my records like in the table below. sql query

My SQL query is

select Category_NM as 'Kategoriler', avg(Payment) as 'Ortalamalar' 
from Islem 
where Category_Type = 'Gider' 
group by Category_NM 

And my code:

public SqlDataReader DataReader(string Query_)
{
    SqlCommand cmd = new SqlCommand(Query_, con);
    SqlDataReader dr = cmd.ExecuteReader();
    return dr;
}

and

SqlDataReader dr = sınıf.DataReader("select Category_NM as 'Kategoriler',AVG(Payment) as 'Ortalamalar' from Islem where Category_Type = 'Gider' group by Category_NM");
dr.Read();

chart1.Series[0].IsValueShownAsLabel = true;

while (dr.Read())
{
    // MessageBox.Show(Convert.ToString(dr[0] "" dr[1]));
    chart1.Series[0].Points.AddXY(dr[0],dr[1]);
}
dr.Close();

The problem ıs reader does not read all records - like this:

enter image description here

CodePudding user response:

Because you call dr.Read() at the first go and then iterate them.

Correction:

SqlDataReader dr = sınıf.DataReader("select Category_NM as 'Kategoriler',AVG(Payment) as 'Ortalamalar' from Islem where Category_Type = 'Gider' group by Category_NM");
chart1.Series[0].IsValueShownAsLabel = true;
while (dr.Read())
{
    // MessageBox.Show(Convert.ToString(dr[0] "" dr[1]));
    chart1.Series[0].Points.AddXY(dr[0], dr[1]);
}
dr.Close();

each Read() move the row pointer ahead. So first Read() skip first record.

If you need check if there is any record and then chart1.Series[0].IsValueShownAsLabel = true; it is enough to use if (dr.HasRows) like:

if(dr.HasRows)
{
   chart1.Series[0].IsValueShownAsLabel = true;
   //Iterate dr like while(dr.Read()){...}
}

But you have to know that your while block logic always read a Record at position 0 and fetch values at col0 and col1, if you need read all record you can iterate by foreach or for something like:

foreach (DbDataRecord s in dr)
 {
    string kategoriler= s.GetString(0);
    string ortalamalar = s.GetString(1);
 }

or while:

while(dr.Read())
{
    var kat = dr["Kategoriler"].ToString();
    var ort = dr["Ortalamalar"].ToString();
}
  • Related