I am following this post, to build a bar chart and show on my webpage. Below is the code i have done to accomplish it:
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString);
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandText = "select * from ForChart";
cmd.CommandType = CommandType.Text;
SqlDataAdapter adp = new SqlDataAdapter();
adp.SelectCommand = cmd;
DataSet myDataSet = new DataSet();
adp.Fill(myDataSet, "Query");
foreach (DataRow row in myDataSet.Tables["Query"].Rows)
{
string seriesName = row["SalesRep"].ToString();
Chart1.Series.Add(seriesName);
Chart1.Series[seriesName].ChartType = SeriesChartType.Line;
Chart1.Series[seriesName].BorderWidth = 2;
for (int colIndex = 1; colIndex < myDataSet.Tables["Query"].Columns.Count; colIndex++)
{
string columnName = myDataSet.Tables["Query"].Columns[colIndex].ColumnName;
string YVal = Convert.ToString(row[columnName]);
Chart1.Series[seriesName].Points.AddXY(columnName, YVal);
}
}
GridView1.DataSource = myDataSet;
GridView1.DataBind();
cmd.Connection.Close();
And my table is having the below data. Please check the snapshot
But when i run the code i am getting the below error. Please help me to resolve the issue:
A chart element with the name 'John' already exists in the 'SeriesCollection'.
I am not able to traverse the records thats why i am getting this error, but i don't know how to traverse through all the records.
Coding help would be very much appreciated. Thanks.
I'm assuming that Chart1.Series requires unique names, and thus this call will fail when you try to enter the same name multiple times:
Chart1.Series.Add(seriesName);
Ugh, that entire example on MSDN is filled with bad practices:
select *
no usings used with SqlConnection, SqlCommand,...
mixing UI code and DB code (they should be in separate classes)
Look at this example for a possible solution.
Related
I am coding win form app, which checks on startup right of the currently logged user. I had these right saved in MS SQL server in the table. When importing data to Datatable, there is no problem. But when I want to read value, there is message "cannot find column xy".
SqlDataAdapter sdaRights = new SqlDataAdapter("SELECT * FROM rights WHERE [user]='" + System.Security.Principal.WindowsIdentity.GetCurrent().Name + "'", conn);
DataTable dtRights = new DataTable(); //this is creating a virtual table
sdaRights.Fill(dtRights);
Object cellValue = dt.Rows[0][1];
int value = Convert.ToInt32(cellValue);
MessageBox.Show(value.ToString());
I would like, that program would save the value from SQL to int.
You are assuming that you have rows being returned, would be my first guess. You should loop through your DataTable instead of simply trying to access element 0 in it.
DataTable dtRights = new DataTable();
sdaRights.Fill(dtRights);
foreach(DataRow row in dtRights.Rows) {
Object cellValue = row[1];
int value = Convert.ToInt32(cellValue);
MessageBox.Show(value.ToString());
}
using (SqlConnection con = new SqlConnection("your connection string"))
{
using (SqlCommand cmd = new SqlCommand("SELECT [column_you_want] FROM [rights] WHERE [user] = #user"))
{
cmd.Parameters.AddWithValue("#user", System.Security.Principal.WindowsIdentity.GetCurrent().Name);
con.Open();
int right = Convert.ToInt32(cmd.ExecuteScalar());
}
}
I am trying to drop down box in design but in database table category has duplicates. I tried to execute by using below code. But it is not executing. It just receiving all commands which I have been changes in properties:
cmd.CommandText = #"Select Distinct Category_Desc from
Database***name order
by Category_Desc";
adapter.SelectCommand = cmd;
SqlDataReader dr1 = cmd.ExecuteReader();
dr1.Read();
comboBoxCategory.ValueMember = "Category_Desc";
comboBoxCategory.DisplayMember = "Category_Desc";
comboBoxCategory.DataSource = dr1;
dr1.Dispose();
Can anyone please help how to execute distinct query from the code?
Data reader is a forward only cursor that you have to iterate and close after the last item.Look at this code segment
SqlDataReader dr1= command.ExecuteReader();
ArrayList arl= new ArrayList();
while (dr1.Read())
{
arl.Add(dr1("Category_Desc"));
}
dr1.close();
//If its a winform project use this
string [] str = al.ToArray(typeof(string));
FarPoint.Win.Spread.ComboBoxCellType cb = new
FarPoint.Win.Spread.ComboBoxCellType();
cb.Items = arl;
Use the adapter to fill a DataTable instead. You already have the adapter and it already has the SelectCommand assigned.
adapter.SelectCommand = cmd;
System.Data.DataTable dtCategories = new System.Data.DataTable();
adapter.Fill(dtCategories);
comboBoxCategory.ValueMember = "Category_Desc";
comboBoxCategory.DisplayMember = "Category_Desc";
comboBoxCategory.DataSource = dtCategories;
I want to arrange the Field Names as user wants to display. I am not using SqlDataSource. I am calling the stored procedure by programming like below.
string cs = ConfigurationManager.ConnectionStrings["HQMatajerConnectionString"].ConnectionString;
using (SqlConnection con = new SqlConnection(cs))
{
SqlCommand cmd = new SqlCommand("spGetTotalSalesQuantity",con);
cmd.CommandType = System.Data.CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#DateFrom", DateFromStr);
cmd.Parameters.AddWithValue("#DateTo", DateToStr);
//cmd.Parameters.AddWithValue("#DateFrom", "2015-01-01 00:00:00");
//cmd.Parameters.AddWithValue("#DateTo", "2015-12-31 23:59:59");
con.Open();
SqlDataAdapter sda = new SqlDataAdapter(cmd);
sda.Fill(ds);
ASPxGridView1.DataSource = ds;
ASPxGridView1.DataBind();
}
In result, I can see the field name how i have given the Column_name in my query. But, User wants to see the Field Name how they are arranging.
For Example:
select
student_id,student_name ,Class,School_Name
From
Student_Details
If above one is my stored procedure. I will get the Field Name how I mentioned in my query.
But User wants to see the result how they are giving. If user give School_Name,Class,Student_id,School_Name.
Is there anyway to arrange in AspxGridView?
Check my answer Based on my understanding of the question and #mohamed's comment.
Try to use the DataColumn.SetOrdinal method. For example:
con.Open();
SqlDataAdapter sda = new SqlDataAdapter(cmd);
sda.Fill(ds);
ds.Tables[0].Columns["School_Name"].SetOrdinal(0);
ds.Tables[0].Columns["Class"].SetOrdinal(1);
ds.Tables[0].Columns["Student_id"].SetOrdinal(2);
ds.Tables[0].Columns["School_Name"].SetOrdinal(3);
ASPxGridView1.DataSource = ds;
ASPxGridView1.DataBind();
even if user changes the select statement order of columns will not change.
Use the hiddentext field and get the column names as user wants to display in which order.
string selectedColumns = HiddentxtSelectedColumn.Value;
Move the selectedColumns to array
string[] names = selectedColumns.Split(',');
sda.Fill(ds);
for (int i = 0; i < names.Length; i++)
{
ds.Tables[0].Columns[names[i]].SetOrdinal(i);`
}
ASPxGridView1.DataSource = ds;
ASPxGridView1.DataBind();
Now It will run exactly.
Is there a way to map the results of a stored procedure to a generic list instead of a dataset/datatable?
Currently I follow these steps:
Execute stored procedure
Take the result in Dataset
Populate list from the Dataset.
Is there a way to eliminate step (2).
OleDbCommand cm = new OleDbCommand();
cm.Connection = AccessConnection();
cm.CommandType = CommandType.StoredProcedure;
cm.CommandText = "seltblContacts";
OleDbDataAdapter adp = new OleDbDataAdapter(cm);
DataTable dt = new DataTable();
adp.Fill(dt);
List<tblContacts> LstFile = new List<tblContacts>();
if (dt.Rows.Count > 0)
{
tblContacts t;
foreach (DataRow dr in dt.Rows)
{
t = PopulateContacts(dr);
LstFile.Add(t);
}
}
Yes of course you can do that - just execute your command and get back a reader, and then iterate over the rows in the result set and build up your objects:
using (OleDbCommand cm = new OleDbCommand())
{
cm.Connection = AccessConnection();
cm.CommandType = CommandType.StoredProcedure;
cm.CommandText = "seltblContacts";
List<tblContacts> LstFile = new List<tblContacts>();
using (OleDbReader reader = cm.ExecuteReader())
{
while(reader.Read())
{
tblContacts contact = new tblContacts();
// here, set the properties based on your columns from the database
contact.FirstName = reader.GetString(0);
contact.LastName = reader.GetString(1);
// etc.
LstFile.Add(contact);
}
reader.Close();
}
return LstFile;
}
For details on OleDbReader and how to use it, see this other SO question or find tons of tutorials and samples online using Bing or Google.
The following coding doesn't update my table. But rows variable value is 1 after updating.
I cannot understand what is the cause behind this. Please help.
SqlConnection connection1 = new SqlConnection(connectionString);
connection1.Open();
var wktbl = new DataTable();
var cmd = new SqlCommand("SELECT * FROM Test", connection1);
var da1 = new SqlDataAdapter(cmd);
var b = new SqlCommandBuilder(da1);
da1.Fill(wktbl);
wktbl.Rows[0][2] = "5";
da1.UpdateCommand = b.GetUpdateCommand(true);
int rows = da1.Update(wktbl);
Check this page out. It shows the example below of doing an update with the dataadapter.
The following examples demonstrate how to perform updates to modified rows by explicitly setting the UpdateCommand of a DataAdapter and calling its Update method. Notice that the parameter specified in the WHERE clause of the UPDATE statement is set to use the Original value of the SourceColumn. This is important, because the Current value may have been modified and may not match the value in the data source. The Original value is the value that was used to populate the DataTable from the data source.
private static void AdapterUpdate(string connectionString)
{
using (SqlConnection connection =
new SqlConnection(connectionString))
{
SqlDataAdapter dataAdpater = new SqlDataAdapter(
"SELECT CategoryID, CategoryName FROM Categories",
connection);
dataAdpater.UpdateCommand = new SqlCommand(
"UPDATE Categories SET CategoryName = #CategoryName " +
"WHERE CategoryID = #CategoryID", connection);
dataAdpater.UpdateCommand.Parameters.Add(
"#CategoryName", SqlDbType.NVarChar, 15, "CategoryName");
SqlParameter parameter = dataAdpater.UpdateCommand.Parameters.Add(
"#CategoryID", SqlDbType.Int);
parameter.SourceColumn = "CategoryID";
parameter.SourceVersion = DataRowVersion.Original;
DataTable categoryTable = new DataTable();
dataAdpater.Fill(categoryTable);
DataRow categoryRow = categoryTable.Rows[0];
categoryRow["CategoryName"] = "New Beverages";
dataAdpater.Update(categoryTable);
Console.WriteLine("Rows after update.");
foreach (DataRow row in categoryTable.Rows)
{
{
Console.WriteLine("{0}: {1}", row[0], row[1]);
}
}
}
}
I found the problem. It's because connectionString has |DataDirectory|.
The MDF file location is different when running the application.