Duplicate values of every data row - c#

There are 2 rows in my table and I'm receiving values within my site as follows:
I should only be receiving 2 rows so I'm not sure what I've done wrong with my code?
if (binForm.Rows.Count != 0)
{
int rowCounter = binForm.Rows.Count;
int increment = 0;
while (rowCounter > 0)
{
tableData.Append("<tr><td>" + binForm.Rows[increment]["binType"].ToString() + "</td><td>" + binForm.Rows[increment]["binColour"].ToString() + "</td><td>" + binForm.Rows[increment]["date"].ToString() + "</td><tr>");
increment++;
rowCounter--;
}
}
This is how the form is generated:
DataTable binForm = new DataTable();
MySqlDataAdapter dataAdapter = new MySqlDataAdapter("SELECT bin.binType, bin.binColour, missedbin.date FROM bin INNER JOIN missedbin ON missedbin.address_addressID=bin.address_addressID WHERE '" + sessionVarAddress.ToString() + "' = bin.address_addressID ", connect);
dataAdapter.Fill(binForm);
here is the actual data in the bin table.
and missedbin table.
EDIT: It seems as though as suggested my sql query is incorrect as it is returning 4 rows.

The problem will be the join, not this snip-it of code.
if you join on a field with 2 entries the same, it will double up as per this example. please go back and check your query.

Related

{"Message":"Cannot find column [AbDate].","StackTrace":" at System.Data.NameNode.Bind(DataTable table, List`1 list) Error

I am using webmethod to load data . I want to check a particular data is existing or not in this data. So, I bind it to a datatable . But I found an error in the network as
{"Message":"Cannot find column [AbDate].","StackTrace":" at
System.Data.NameNode.Bind(DataTable table, List1 list).
But the column AbDate is existing. I am sure because I check the values using break point .
[WebMethod]
public static IList GetEvents(string Start, string End, double OS_Idno, double Gs_Id, string AccYear, double Sid)
{
DataSet ds = new DataSet();
DataTable dt1 = new DataTable();
SqlDataAdapter sda = new SqlDataAdapter("My query", con);
sda.Fill(dt1);
ds.Tables.Add(dt1);
for (int i = 0; i < dt1.Rows.Count; i++)
{
DateTime AttDate = Convert.ToDateTime(dt1.Rows[i]["OSA_Dateofattendance"]);
DataRow[] Date1 = ds.Tables[0].Select("AbDate='" + AttDate + "' and Os_idno='" + OS_Idno + "'");
if (Date1.Count() == 0)
{
}
else
{
}
}
}
But when I change the code as
DataRow[] Date1 = ds.Tables[0].Select("Os_idno='" + OS_Idno + "'");
It works for me . And the main issue is the problem is not in my local only in the server. I have a full calendar to show this results. In the console I found a error as
Failed to load resource: the server responded with a status of 500 (Internal Server Error)
Please help I don't have an idea what to do
I think you must change your query such as:
SELECT AbDate AS AD …
and use AD instead of AbDate in your filtering
like this:
DataRow[] Date1 = ds.Tables[0].Select("AD='" + AttDate + "' and Os_idno='" + OS_Idno + "'");

Last value selection in SQL-Server

I am trying to select last values of the columns in the datatable from the SQL Server Database.
My code is
private void bind_chart()
{
// here i am using SqlDataAdapter for the sql server select query
SqlDataAdapter adp = new SqlDataAdapter("select last() * from Test", con);
// here am taking datatable
DataTable dt = new DataTable();
try
{
// here datatale dt is fill wit the adp
adp.Fill(dt);
// this string m catching in the stringbuilder class
// in the str m writing same javascript code that is given by the google.
// my data that will come from the sql server
// below code is same like as google's javascript code
str.Append(#" <script type='text/javascript'>
google.load('visualization', '1', {packages:['gauge']});
google.setOnLoadCallback(drawChart);
function drawChart() {
var data = new google.visualization.DataTable();
data.addColumn('string', 'Label');
data.addColumn('number', 'Value');");
// inside the below line dt.Rows.Count explain that
// how many rows comes in dt or total rows
str.Append("data.addRows(" + dt.Rows.Count + ");");
Int32 i;
for (i = 0; i <= dt.Rows.Count - 1; i++)
{
// i need this type of output " data.setValue(0, 0, 'Memory'); so on in the first line so for this
//m using i for the 0,1& 2 and so on . and after this i am writting zero and after this student_name using datatable
str.Append("data.setValue( " + i + "," + 0 + "," + "'" + dt.Rows[i]["x"].ToString() + "');");
// i need this type of output " data.setValue(0, 1, 80);
//so on in the first line so for this
//m using i for the 0,1& 2 and so on . and after this i am writting zero and after this percentage using datatable
str.Append("data.setValue(" + i + "," + 1 + "," + dt.Rows[i]["y"].ToString() + ") ;");
// str.Append("['" + (dt.Rows[i]["student_name"].ToString()) + "'," + dt.Rows[i]["average_marks"].ToString() + "],");
}
str.Append("var chart = new google.visualization.Gauge(document.getElementById('chart_div'));");
// in the below line i am setting the height and width of the Gauge using your own requrirement
str.Append(" var options = {width: 800, height: 300, redFrom: 90, redTo: 100,");
// str.Append(" var chart = new google.visualization.BarChart(document.getElementById('chart_div'));");
str.Append("yellowFrom: 75, yellowTo: 90, minorTicks: 5};");
str.Append("chart.draw(data, options);}");
str.Append("</script>");
lt.Text = str.ToString().TrimEnd(',');
}
catch
{
}
finally
{
}
}
And want to display the last value on the gauge.
Here I am not getting the last value from the query I generated. I dont know why.
Best and recommended method.
select top 1 * from test order by ID desc
I think Last() is not a function of sql-server
But you can get the last row by using my below way's .Try this
SELECT * FROM TableName WHERE PrimaryKeyId= (SELECT MAX(PrimaryKeyId) FROM TableName )
or , try another way.
SELECT TOP 1 * FROM TableName ORDER BY PrimaryKeyId DESC
make sure set identity for your primary key .
SQL Server doesn't support LAST() syntax. Instead you can use another approach described here - http://www.w3schools.com/sql/sql_func_last.asp

Getting error while looping through dataset

I'm using VS 2012 C#. I'm trying to loop through datasets to get information from an Access database. I have a combobox that when an item is selected it should print out all the data for that given scenario. For some the the values in the combobox I get the error, "The SelectCommand property has not been initialized before calling 'Fill'." But for some of the other values I don't and the information is retrieved without an issue. Here is all the necessary code,
con2.Open();
ad2 = new OleDbDataAdapter(query, con2);
ad2.Fill(ds2, "AC_SCENARIO");
con2.Close()
try
{
string end = "ENDDATE";
string start = "START";
foreach (DataRow drRow in ds2.Tables[0].Rows)
{
for (int i = 0; i <= ds2.Tables[0].Columns.Count; i++)
{
string qual0 = ds2.Tables["AC_SCENARIO"].Rows[i]["QUAL0"].ToString();
string qual1 = ds2.Tables["AC_SCENARIO"].Rows[i]["QUAL1"].ToString();
string qual2 = ds2.Tables["AC_SCENARIO"].Rows[i]["QUAL2"].ToString();
string qual3 = ds2.Tables["AC_SCENARIO"].Rows[i]["QUAL3"].ToString();
string qual4 = ds2.Tables["AC_SCENARIO"].Rows[i]["QUAL4"].ToString();
//HERE IS A SAMPLE QUERY
if (qual0 != null && (string)comboBox1.SelectedItem == qual0)
{
ad.SelectCommand = new OleDbCommand("SELECT b.RSV_CAT, b.SEQNUM, b.LEASE, b.WELL_ID, a.QUALIFIER, a.KEYWORD, a.EXPRESSION FROM [AC_ECONOMIC] a INNER JOIN [AC_PROPERTY] b on a.PROPNUM=b.PROPNUM WHERE a.KEYWORD = '"
+ end + "' AND (a.QUALIFIER = '" + qual0 + "' OR a.QUALIFIER IS NULL) AND NOT a.EXPRESSION Like '%[/#]%'", con);
}
ds.Clear();
ad.Fill(ds); //The SelectCommand property has not been initialized before calling 'Fill'.
//ERROR OCCURS HERE
con.Open();
ad.SelectCommand.ExecuteNonQuery();
con.Close();
EDIT: HERE IS THE con CODE
String filePath = textBox1.Text;
con = new OleDbConnection(#"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + filePath);
I have more queries such as those listed for another dataset and then I merge the two datasets together and output them to a datagridview. The error occurs on the line ad.Fill(ds); If anyone can explain this issue to me or has any help that would be great.
Columns collection of DataTable is zero based index and is one less then Count, the loop should be one less then number of columns as first column is at 0 index and last column is columns count-1. You can use < instead of <= in loop condition to iterate from zero to Count-1.
Change
for (int i = 0; i <= ds2.Tables[0].Columns.Count; i++)
To
for (int i = 0; i < ds2.Tables[0].Columns.Count; i++)
Creation of con is also not present in the code you have in OP
the problem is probably here
if (qual0 != null && (string)comboBox1.SelectedItem == qual0)
In some scenarios the if loop turns out to be true and ad.SelectCommand will get initialized.
EDIT
Are you sure the Select Command is forming correctly for every values of qual0.
Please try using named parameters while forming the query . the qual variable might be having some ' in it that prevent your query getting formed correctly..
EDIT
qual0.Replace("'","\"");
You've not provided a default case for if qual0 is null.
I'm going to assume that you do this multiple times and it's not just the one qual variable you check and build a statement for, if that's the case then you might be better off refactoring to something like this:
if (qual0 != null && (string)comboBox1.SelectedItem == qual0)
{
ad.SelectCommand = new OleDbCommand("SELECT b.RSV_CAT, b.SEQNUM, b.LEASE, b.WELL_ID, a.QUALIFIER, a.KEYWORD, a.EXPRESSION FROM [AC_ECONOMIC] a INNER JOIN [AC_PROPERTY] b on a.PROPNUM=b.PROPNUM WHERE a.KEYWORD = '"
+ end + "' AND (a.QUALIFIER = '" + qual0 + "' OR a.QUALIFIER IS NULL) AND NOT a.EXPRESSION Like '%[/#]%'", con);
}
if (ad.SelectCommand != null)
{
if (!String.IsNullOrEmpty(ad.SelectCommand.CommandText))
{
ds.Clear();
ad.Fill(ds);
}
}

How to present the data from multiple DataTables in a series of stacked data grids?

I have an undefined amount of DataTables. I get them from my DataBase, each DataTable stands for one Table in my DataBase, I dont use all Tables of the DataBase just the few I need (these were selectet earlier in the code) and not all columns (same like the tables).
Now my problem: I want to show them in a DataGrid one below the other with breaks between them for the tablename.
This is how i get my DataTables:
List<DBTable> selectedTbl = DBObject.SingDBObj.GetSelectedTables();
foreach (DBTable tbl in selectedTbl)
{
string cols = tbl.GetSelectedColumnNames();
string query = #"SELECT " + cols + " FROM [" + DBObject.SingDBObj.DataSource + "].[" + DBObject.SingDBObj.Database + "].[" + tbl.Schema + "].[" + tbl.Name + "];";
DataTable DTShow = DBObject.SingDBObj.ExecuteQuery(query);
}
dataGridShowColmns.DataContext = ??;
Is there an easy way to do this?
You maybe mean something like:
DataSet ds = new DataSet();
// dataset is here just initialized for demonstration, you would first
// get the tables from database and populate dataset
for (int i = 0; i < ds.Tables.Count; i++)
{
DataTable dt = ds.Tables[i];
foreach (DataRow dr in dt.Rows)
{
dataGridView1.Rows.Add(dr);
}
}
In SQL name to a dataset cannot be assigned, only way you can do it in c#/VB. like
Dataset.Table[0].Name = "MyTable";

Why am I getting a NullReferenceException on a DataSet?

I'm opening up a database query from the Northwind database for each item that my ShoppingCart entails. It is to take ProductID and UnitsInStock out from the Products table. After I take the two columns out from the database to save the data into a DataTabel ds. Then I compare to make sure the quantity user entered is less than the column units in stock in the database.
theCart.Values is part of ICollections.
I am gettign error: from my exception message: "There was a problem connecting to the database: Object reference not set to an instance of an object."
Here's the code.
DataSet ds = new DataSet();
OleDbConnection conn = new OleDbConnection((string)Application["DBConnectionString"]);
foreach (OrderItem item in theCart.Values)
{
string selectionString =
"SELECT Products.ProductID, Products.UnitsInStock " +
"FROM Products" +
"WHERE Products.ProductID = " + item.ProductID + ";";
try
{
OleDbCommand cm = new OleDbCommand(selectionString, conn);
OleDbDataAdapter da = new OleDbDataAdapter();
da.SelectCommand = cm;
da.Fill(ds);
da.Dispose();
if (ds.Tables["Products"].Columns.Count != 0 &&
ds.Tables["Products"].Rows.Count != 0)
{
for (int index = 0; index < ds.Tables["Products"].Rows.Count; index++)
{
if (item.ProductID == int.Parse(ds.Tables["Products"].Rows[index][indexOfProductID].ToString()))
{
if (item.QuantityOrdered > int.Parse(ds.Tables["Products"].Rows[index][indexOfUnitsInStock].ToString()))
{
hasStock = false;
int inStock = int.Parse(ds.Tables["Products"].Rows[index][indexOfUnitsInStock].ToString());
txtUnderstockedItems.Text += "Sorry we do not have enough stock of item: " + item.ProductName +
"<br> Currently, " + item.ProductName + " (ID:" + item.ProductID + ") has " + inStock + " in stock.";
}
else
{//can output how many items in stock here.
hasStock = true;
}
}
}
}
catch (Exception ex)
{
txtUnderstockedItems.Text = "There was a problem connecting to the database: " + ex.Message;
}
finally
{
conn.Close();
}
}
}
Rows or Columns is most likely null. Inspect ds prior to that if statement. A common reason something like this would happen is that the Products table returned nothing. You can't get the property of an object that does not exist, thus the exception. You should do a != null comparison instead of checking the count. If the length is zero the code inside the loop will never execute but you won't crash or anything.
if (ds.Tables["Products"].Columns != null && ds.Tables["Products"].Rows != null)
Just a heads up, this will cause no problems if your row count is zero, but you may need some logic within the loop to check that the columns you're planning to access exist.
You are trying to get the table from the dataset with its hardcoded name as to what you see in the database, I just ran a test on a similar pattern and it looks like when you create a Dataset and fill it from the database as you are doing, the table name is not copied from the Database. As Tim suggested, you should check for ds.Table[0]
DataTableCollection.Item returns null if there's no table with the specified table-name.
If a command does not return any rows, no tables are added to the DataSet, and no exception is raised. So i assume that there's no table in the DataSet because no rows are returned.
I would initialize a single DatatTable manually instead and use the overload of Fill which takes a DataTable.
Dim table = new DataTable("Products")
da.Fill(table)

Categories