not able to use two dataset on same .aspx.cs page - c#

I am using two Datasets on this page 1.DsCountry(in BindCountry()) and 2.DsState(in BindState()) but data from the database is getting filled only in DsCountry not in DsState but when BindCountry() is commented DsState is working.
public void BindCountry()
{
objCountry.SortOn = Convert.ToString(ViewState["SortOn"]);
objCountry.SortBy = Convert.ToString(ViewState["SortBy"]);
DataSet DsCountry = objCountry.GetAllCountryDetails();
ddlCntry.DataSource = DsCountry.Tables[0];
ddlCntry.DataValueField = "CountryId";
ddlCntry.DataTextField = "CountryName";
ddlCntry.DataBind();
}
public void BindState()
{
objState.CountryId = int.Parse(ddlCntry.SelectedItem.Value);
objState.StateName = txtState.Text.Trim();
objState.SortOn = ViewState["SortOnState"].ToString();
objState.SortBy = ViewState["SortByState"].ToString();
DataSet DsState = objState.getStates();
gvState.DataSource = DsState;
gvState.DataBind();
}

In here:
public void BindState()
{
objState.CountryId = int.Parse(ddlCntry.SelectedItem.Value);
objState.StateName = txtState.Text.Trim();
objState.SortOn = ViewState["SortOnState"].ToString();
objState.SortBy = ViewState["SortByState"].ToString();
DataSet DsState = objState.getStates();
gvState.DataSource = DsState;
gvState.DataBind();
}
on this line:
gvState.DataSource = DsState;
if this is a dataset (implies it has multiple tables in it), then you need to specify a specific table you want to bind to, just like in your country method:
ddlCntry.DataSource = DsCountry.Tables[0];
will become this:
gvState.DataSource = DsState.Tables[0];
Assuming you return only one table in the dataset.
otherwise its like: go get me something I do not know what. :)

Your BindState Code should be like this
public void BindState()
{
objState.CountryId = int.Parse(ddlCntry.SelectedItem.Value);
objState.StateName = txtState.Text.Trim();
objState.SortOn = ViewState["SortOnState"].ToString();
objState.SortBy = ViewState["SortByState"].ToString();
DataSet DsState = objState.getStates();
gvState.DataSource = DsState.Tables[0];
gvState.DataBind();
}
You can apply more than 1 dataset in 1 page.

Related

DataSet not saving the data

This is the first time I am using DataSet. Below is my code
var transactionSet = new ModelExecutionContext()
{
TransactionSet = new DataSet()
{
Tables = { new DataTable()
{
TableName = "transaction_history"
}
}
}
};
transactionSet.TransactionSet.Tables["transaction_history"].Columns.Add().ColumnName = "retailer_reference_id";
var retailerReferenceIdRow = transactionSet.TransactionSet.Tables["transaction_history"].NewRow();
retailerReferenceIdRow["retailer_reference_id"] = 8;
transactionSet.TransactionSet.AcceptChanges();
I am unit testing a method in a class which has the datasets. I am trying to mock those datasets. I thought transactionSet.TransactionSet.AcceptChanges(); will save the changes into the DataSet, but in the execution, I am getting context?.TransactionSet?.Tables["transaction_history"]?.Rows.Count = 0
Is anything incorrect with my code?
After you created object of row you need to add row to table.
transactionSet.TransactionSet.Tables["transaction_history"].Rows.Add(retailerReferenceIdRow);

Not getting BarChart in Winform Application

I am trying to show a dynamic barchart from database in winform application but it is not coming and giving me Argument out of Exception error at var p2 = series.Points[arrlocationSTD]; when arrlocationSTD=1. Here is my code in c#..
void LoadBarChart(string qurystring)
{
if (calltype.Equals("TRANSFERED"))
{
totalTransfered = dr["SummaryOfCalls"].ToString();
intTRANSFERED = int.Parse(totalTransfered, CultureInfo.InvariantCulture);
if (i == 0)
{
arrlocationTransferred = i;
series.Points.Add(intTRANSFERED);
var p7 = series.Points[arrlocationTransferred];
p7.Color = Color.Yellow;
p7.AxisLabel = "TRANSFERED";
p7.LegendText = "TRANSFERED";
p7.Label = totalTransfered;
i++;
}
else
{
arrlocationTransferred = i;
series.Points.Add(intTRANSFERED);
var p7 = series.Points[arrlocationTransferred];
p7.Color = Color.Yellow;
p7.AxisLabel = "TRANSFERED";
p7.LegendText = "TRANSFERED";
p7.Label = totalTransfered;
}
}
}
barChart.Invalidate();
pnlBar.Controls.Add(barChart);
}
Please help me to resolve this.
Thanks in advance..
You'll need to add your additional processing, but the following might help.
I'd strongly recommend that you get the chart showing your data correctly before you start changing colour properties and such.
void LoadBarChart(string qurystring)
{
String conn = Strings.ConnectionString; // You fill this in.
Dictionary<String,int> callSummariesByTypeOfCall =
new Dictionary<String,int>();
MySqlConnection con = new MySqlConnection(conn);
MySqlCommand comm = new MySqlCommand(qurystring, con);
con.Open();
MySqlDataReader dr = comm.ExecuteReader();
// Get the data into a dictionary
while (dr.Read())
{
String calltype = dr["TypeOfCall"].ToString();
int summary = int.Parse(dr["Calls"].ToString(), CultureInfo.InvariantCulture);
callSummariesByTypeOfCall[calltype] = summary;
}
// Do any other processing you need here
// Bind the data onto the Series
Series series = new Series
{
Name = "series2",
IsVisibleInLegend = false,
ChartType = SeriesChartType.Column
};
series.Points.DataBindXY(
callSummariesByTypeOfCall.Keys,
callSummariesByTypeOfCall.Values);
barChart.Series.Add(series);
barChart.Invalidate();
pnlBar.Controls.Add(barChart);
}

How to add new items to combobox which is bound to Entities?

Design class which is generated by C# :
//
// usepurposeComboBox
//
this.usepurposeComboBox.DataSource = this.usepurposeBindingSource;
this.usepurposeComboBox.DisplayMember = "Name";
this.usepurposeComboBox.FormattingEnabled = true;
this.usepurposeComboBox.Location = new System.Drawing.Point(277, 53);
this.usepurposeComboBox.Name = "usepurposeComboBox";
this.usepurposeComboBox.Size = new System.Drawing.Size(218, 21);
this.usepurposeComboBox.TabIndex = 4;
this.usepurposeComboBox.ValueMember = "id";
//
// usepurposeBindingSource
//
this.usepurposeBindingSource.DataSource = typeof(mydatabaseEntities.usepurpose);
Then I bound the BindingSource (usepurposeBindingSource) to Entities :
usepurposeBindingSource.DataSource = mydatabaseEntities.usepurposes;
And I can not add a new row to usepurposeComboBox because it's been bound. Is there a workaround ?
The shortest way is to add a new row to your dataTable and then bind your comboBox to it something like this:
Company comps = new Company();
//pupulate dataTable with data
DataTable DT = comps.getCompaniesList();
//create a new row
DataRow DR = DT.NewRow();
DR["c_ID"] = 0;
DR["name"] = "Add new Company";
DR["country"] = "IR";
//add new row to data table
DT.Rows.Add(DR);
//Binding DataTable to cxbxCompany
cxbxCompany.DataSource = DT;
cxbxCompany.DisplayMember = "name";
cxbxCompany.ValueMember = "c_ID";
I'm assuming that you want to add for example a first item sometimes called "Choose One" as if you want to live data you should just see where the data comes from and add more items to that "table".
this.usepurposeBindingSource is an object ... why not adding into it before it binds?
if it's a List<T> this will be fine
this.usepurposeBindingSource.Insert(0, new T() {
Name = "Choose one",
Id = ""
});
Then Bind() it...
Remember to validate as it's a string and will not be the object you want
This is working:
List<MyObject> usepurposeBindingSource { get; set; }
private void FillUpData()
{
// Simulating an External Data
if (usepurposeBindingSource == null || usepurposeBindingSource.Count == 0)
{
this.usepurposeBindingSource = new List<MyObject>();
this.usepurposeBindingSource.Add(new MyObject() { Name = "A", ID = 1 });
this.usepurposeBindingSource.Add(new MyObject() { Name = "B", ID = 2 });
this.usepurposeBindingSource.Add(new MyObject() { Name = "C", ID = 3 });
}
}
private void FillUpCombo()
{
FillUpData();
// what you have from design
// comment out the first line
//this.usepurposeComboBox.DataSource = this.usepurposeBindingSource;
this.usepurposeComboBox.DisplayMember = "Name";
this.usepurposeComboBox.FormattingEnabled = true;
this.usepurposeComboBox.Location = new System.Drawing.Point(277, 53);
this.usepurposeComboBox.Name = "usepurposeComboBox";
this.usepurposeComboBox.Size = new System.Drawing.Size(218, 21);
this.usepurposeComboBox.TabIndex = 4;
this.usepurposeComboBox.ValueMember = "id";
// to do in code:
this.usepurposeBindingSource.Insert(0, new MyObject() { Name = "Choose One", ID = 0 });
// bind the data source
this.usepurposeComboBox.DataSource = this.usepurposeBindingSource;
}
The trick is to comment out the DataSource line and do it in your code, inserting one more element into your object that is from your Model
//this.usepurposeComboBox.DataSource = this.usepurposeBindingSource;
The simplest way to do this, is to wrap your BindingSource with some kind of "ViewModel". The new class will return a "complete" list of items - both those provided from the original binding source, as well as those "additional" items.
You can then bind the new wrapper to your combobox.
I wrote an article about this a while back... It's not my finest work, and it's probably a bit outdated, but it should get you there.
I resolved it on my own. I created a new unbound combobox then bind it to a datatable. Not sure if it's the best way but it works for me. Thanks for all of your suggestions. :)
private void FillCombobox()
{
using (mydatabaseEntities mydatabaseEntities = new mydatabaseEntities())
{
List<usepurpose> usepurposes = mydatabaseEntities.usepurposes.ToList();
DataTable dt = new DataTable();
dt.Columns.Add("id");
dt.Columns.Add("Name");
dt.Rows.Add(-1, "test row");
foreach (usepurpose usepurpose in usepurposes)
{
dt.Rows.Add(usepurpose.id, usepurpose.Name);
}
usepurposeComboBox.ValueMember = dt.Columns[0].ColumnName;
usepurposeComboBox.DisplayMember = dt.Columns[1].ColumnName;
usepurposeComboBox.DataSource = dt;
}
}
Check out this link: http://forums.asp.net/t/1695728.aspx/1?
In asp you can add this to insert an empty line:
<asp:DropDownList ID="CustomerDropDownList" runat="server"
DataSourceID="CustomerEntityDataSource" DataTextField="CustomerId"
DataValueField="CustomerId" AppendDataBoundItems="true">
<asp:ListItem Text="Select All Customers" Value="" />
</asp:DropDownList>
Or in code behind:
DropDownList1.AppendDataBoundItems = true;
DropDownList1.Items.Add(new ListItem("Select All Customers", "-1"));

BindingSource.Find key comparison is case insensitive?

I'm using BindingSource.Find() to return to the user's position after refreshing a DataGridView. I use BindingSource.Find() and a RowID as the DataColumn I'm searching on. Unfortunately, Oracle can return two RowIDs that differ only in their case.
BindingSource.Find() returns the first match regardless of case.
Looking at the MSDN docs:
public int Find(string propertyName, Object key)
it says that the propertyName comparison is case-insensitive, but does not mention whether the key comparison is.
Does anyone know how to make BindingSource.Find case sensitive?
For a DataView all you should need to do is set the CaseSensitive property of the parent DataTable to true. I just quickly prototyped that with the following code and it works fine:
public Form1()
{
InitializeComponent();
DataSet set1 = new DataSet();
// Some xml data to populate the DataSet with.
string testXml =
"<?xml version='1.0' encoding='UTF-8'?>" +
"<numbers>" +
"<number><name>one</name></number>" +
"<number><name>two</name></number>" +
"<number><name>Two</name></number>" +
"<number><name>three</name></number>" +
"</numbers>";
// Read the xml.
StringReader reader = new StringReader(testXml);
set1.ReadXml(reader);
// Get a DataView of the table contained in the dataset.
DataTableCollection tables = set1.Tables;
// Set the CaseSensetive property
tables[0].CaseSensitive = true;
DataView view1 = new DataView(tables[0]);
// Create a DataGridView control and add it to the form.
dataGridView1.AutoGenerateColumns = true;
// Create a BindingSource and set its DataSource property to
// the DataView.
BindingSource source1 = new BindingSource();
source1.DataSource = view1;
// Set the data source for the DataGridView.
dataGridView1.DataSource = source1;
// Set the Position property to the results of the Find method.
int itemFound = source1.Find("name", "Two");
source1.Position = itemFound;
}
For other types of IBindingList you need, as the docs say, an underlying list that implements a Find which is case sensitive. For completeness I have shown the code to do this below:
public Form1()
{
InitializeComponent();
// This uses my CaseSensitiveBindingList which I have code for later
BindingList<DGVItems> source = new CaseSensitiveBindingList<DGVItems>()
{
new DGVItems { Number = "one" },
new DGVItems{Number = "two"},
new DGVItems{Number = "Two"}
};
BindingSource bindingSource = new BindingSource();
bindingSource.DataSource = source;
dataGridView1.DataSource = bindingSource;
var index = bindingSource.Find("Number", "Two");
// Index is 2 (third item) as desired.
MessageBox.Show(number.ToString());
}
public class DGVItems
{
public string Number { get; set; }
}
And the code for the CaseSensitiveBindingList is:
public class CaseInsensitiveBindingList<T> : BindingList<T>
{
protected override int FindCore(PropertyDescriptor prop, object key)
{
string stringKey = key as string;
bool keyIsString = stringKey != null;
for (int i = 0; i < Count; ++i)
{
if (keyIsString && prop.PropertyType.IsAssignableFrom(typeof(string)))
{
if (stringKey.Equals(prop.GetValue(Items[i]).ToString(), StringComparison.CurrentCulture))
return i;
}
else
{
if (key.Equals(prop.GetValue(Items[i])))
return i;
}
}
return -1;
}
}
That code could almost certainly be improved but shows the general concept.

Select TOP 5 * from SomeTable, using Dataview.RowFilter?

I need to select 5 most recent rows from cached Dataview object, is there any way to do that?
I've tried but Indexer DataColumn is empty. :
public static DataView getLatestFourActive()
{
DataTable productDataTable = getAll().ToTable();
DataColumn ExpressionColumn = new DataColumn("Indexer",typeof(System.Int32));
ExpressionColumn.Unique = true;
ExpressionColumn.AutoIncrement = true;
ExpressionColumn.AllowDBNull = false;
ExpressionColumn.AutoIncrementSeed = 0;
ExpressionColumn.AutoIncrementStep = 1;
productDataTable.Columns.Add(ExpressionColumn);
DataView productFilteredView = productDataTable.DefaultView;
productFilteredView.RowFilter = "isActive=1 and Indexer<4";
return productFilteredView;
}
getAll() returns cached DataView
thanks
I encountered the same sample above in this article, but the last post says the provided code doesn't work.
However, this article has a solution that does work, so here's the code you could use:
public static DataView getLatestFourActive() {
DataTable productDataTable = getAll().ToTable();
DataTable cloneDataTable = productDataTable.Clone();
for (int i = 0; i < 4; i++) {
cloneDataTable.ImportRow(productDataTable.Rows[i]);
}
return new DataView(cloneDataTable);
}
getALL().Take(5);

Categories

Resources