I'm now stuck regarding array comparison and creating it. I have 2 tables, station and location. The columns inside station is the id and the station name. there goes the same to the location table only different is the name. I put the id into a array and the name to the array. I wanted to compare the name and the id so that when user select the name, the program knows which id belongs to the selected name and save it into the other table using their primary keys. Here were the codes that I created from now but I don't know how to solve it. Hope I could get some help here. Thanks!
private void btnCreate_Click(object sender, EventArgs e)
{
using (testEntities Setupctx = new testEntities())
{
string[] stations = StationNameList();
int[] stationsID = StationIDList();
string[] locations = LocationNameList();
int[] locationsID = LocationIDList();
int Stationindex = cbStation.SelectedIndex;
int Locationindex = cbLocation.SelectedIndex;
trolleyservice TS = new trolleyservice();
TS.stationID = cbStation.SelectedIndex;
TS.locationID = cbLocation.SelectedIndex;
TS.tServiceTiming = txtTime.Text;
TS.tServiceType = txtType.Text;
Setupctx.trolleyservices.AddObject(TS);
txtTime.Text = "";
txtType.Text = "";
MessageBox.Show("New Trolley Service Has Been Created.");
}
}
Here were all the arrays that I created for each tables.
private string[] StationNameList()
{
using (testEntities Setupctx = new testEntities())
{
return Setupctx.stations.Select(s => s.Station1).OrderBy(s => s).ToArray();
}
}
private int[] StationIDList()
{
using (testEntities Setupctx = new testEntities())
{
return Setupctx.stations.Select(sid => sid.idstations).OrderBy(sid => sid).ToArray();
}
}
private string[] LocationNameList()
{
using (testEntities Setupctx = new testEntities())
{
return Setupctx.locations.Select(l => l.Location1).OrderBy(l => l).ToArray();
}
}
private int[] LocationIDList()
{
using (testEntities Setupctx = new testEntities())
{
return Setupctx.locations.Select(lid => lid.idlocation).OrderBy(lid => lid).ToArray();
}
}
Here you can do thing, instead of taking two different array of name and id you can take list of station class like this.
private List<stations> StationNameList()
{
using (testEntities Setupctx = new testEntities())
{
return Setupctx.stations.OrderBy(s => s.Station1).ToList();
}
}
now assign this list to cbStation as datasource like this
cbStation.DataSource =StationNameList() ;
cbStation.DataTextField = "Station1";//it is text field that you want to display
cbStation.DataValueField = "idstations";//it is value field of combo box
cbStation.DataBind();
Now use SelectedValue property of conbobox instead of SelectedIndex property you will get
station id that related to station name.
TS.stationID = cbStation.SelectedValue;
Same thing is for location also
you can also use array instead list here.
Related
I wanted get set of data and append to combobox from database using linq.
I have did it already but when i save data. My db saved value looks like this:
{
schid = 1004,
schoolname = St John Bossco
}
I only wanted to save the string value of the school name. how can i approach that?
This is my code:
private void get_combo_vale_list()
{
using (DBEntity db = new DBEntity())
{
var school = db.basicdata_school.Select(x => new { x.schid, x.schoolname });
cmbalschool.DataSource = school.ToList();
cmbalschool.ValueMember = "schid";
cmbalschool.DisplayMember = "schoolname";
cmbalschool.SelectedItem = null
}
}
this is my .csv file:
Apple,rose,tiger
Mango,lily,cheetah
Banana,sunflower,lion
Apple,marigold,cat
input: Mango (i write it in the text box)
desired output:
Flower = lily; Animal = cheetah
similarly,
input: Apple
desired output:
Flower = rose,marigold; Animal = tiger,cat
this is the code i have written:
private void button1_Click(object sender, EventArgs e)
{
using (var reader = new StreamReader(#"C:\asp_net\abc.csv"))
{
List<string> listA = new List<string>();
List<string> listB = new List<string>();
List<string> listC = new List<string>();
while (!reader.EndOfStream)
{
var line = reader.ReadLine();
var values = line.Split(',');
listA.Add(values[0]);
listB.Add(values[1]);
listC.Add(values[2]);
}
string checkThis = obj.SearchSenSig(textBox1.Text);
if (listA.Any(checkThis.Contains))
{
int count = listA.Where(x => x.Equals(checkThis)).Count();
if (count == 1)
{
int index = listA.IndexOf(checkThis);
var firstItem = listB.ElementAt(index);
var secondItem = listC.ElementAt(index);
MessageBox.Show(String.Format("receiver = {0}, url = {1}", firstItem, secondItem));
}
else
{
foreach (string item in listA)
{
int i = listA.IndexOf(item);
bool result = item.Equals(checkThis);
if (result)
{
List<string> myCollection1 = new List<string>();
myCollection1.Add(listB.ElementAt(i));
string firstItem = string.Join(",", myCollection1);
List<string> myCollection2 = new List<string>();
myCollection2.Add(listC.ElementAt(i));
string secondItem = string.Join(",", myCollection2);
MessageBox.Show(String.Format("Flower = {0}, Animal = {1}", firstItem, secondItem));
}
}
}
}
else
{
MessageBox.Show("The search element does not exists.");
}
}
Still i am not getting the desired output. Please help.
Instead of creating a different list for each column, create a single class to hold an entire row data:
class Data // I'll bet you can find a better name for this class...
{
public string Fruit {get;set;}
public string Flower {get;set;}
public string Animal {get;set;}
}
and populate a list of this class:
private List<Data> data = new List<Data>(); // note: this is a field, not a local variable.
Populating this list should be done only once, in the constructor or in the form_load event:
while (!reader.EndOfStream)
{
var line = reader.ReadLine();
var values = line.Split(',');
data.Add(
new Data()
{
Fruit = values[0],
Flower = values[1],
Animal = values[2]
}
);
}
Now all you have to do in the button_click event handler is get all the items corresponding to your search string. Assuming you are only searching for fruits using the FindAll method and display the results:
var result = data.FindAll(d => d.Fruit == searchString);
This will return a list of Data where the Fruit property contains the same string as searchString. use linq and string.Join to format the results into a string:
var resultString = $"Flower = {string.Join(",", result.Select(r => r.Flower))}; Animal = {string.Join(",", result.Select(r => r.Animal))}";
I would like to know how to see the results from a database in text format from LiteDB in the console or a multi line text box when the form loads. This is what I have so far, but it doesn't return the information.
private void DisplayData_Load(object sender, EventArgs e)
{
using (var db = new LiteDatabase(#"C:\Temp\MyData.db"))
{
// Get a collection (or create, if doesn't exist)
var col = db.GetCollection<DataBase>("data");
// Create your new customer instance
var results = col.FindAll();
Console.WriteLine(results);
}
}
I think I found a version of the answer. This code displays the data to a combo box, console output, or as text for a text box...
public class DataBase
{
[BsonId]
public string GetSetVariable { get; set; }
}
private void DisplayData_Load(object sender, EventArgs e)
{
using (var db = new LiteDatabase(#"C:\Temp\MyData.db"))
{
// Get a collection (or create, if doesn't exist)
var col = db.GetCollection<DataBase>("collection_name");
// Enter data into the database
var incomingData = new Database
{
GetSetvariable = "This is output text."
};
// Create unique index in Name field
col.EnsureIndex(x => x.GetSetVariable, true);
// Insert new customer document (Id will be auto-incremented)
col.Insert(incomingData);
// Update a document inside a collection
incomingData.GetSetVariable = "Updated Text Record";
col.Update(incomingData);
// Create a query
var results = col.FindAll();
// To display ALL columns of 'results' in a combo box.
foreach (var finding in results)
{
var variable = finding.GetSetVariable;
comboBox1.Items.Add(variable);
Console.WriteLine(variable);
}
// To display one record of 'results' to a text box.
var query = col.FindById(1);
var variable = query.GetSetVariable;
textBox1.Text = variable;
Console.WriteLine(variable);
}
}
I have a dictionary:
Dictionary<ICD_Map2, string> maps = new Dictionary<ICD_Map2, string>();
I add to the dictionary via button click:
private void button2_Click(object sender, EventArgs e)
{
maps.Clear();
// Load mapping file.
var reader = new StreamReader(File.OpenRead(#"Call_Details_Map.csv"));
while (!reader.EndOfStream)
{
var line = reader.ReadLine();
var values = line.Split(',');
maps.Add(new ICD_Map2(values[0].Replace("\"",""), values[1].Replace("\"","")), values[2].Replace("\"",""));
}
}
I want to use LINQ and map my keys to the "string" in maps.
How do I do it?
var File001 = from line in File.ReadLines(ICD_process)
let l = line.Split(',')
where l[0] != "\"Statement Date\""
select new
{
CallType = maps.ToLookup(p => l[5], p => l[3]),
Calls = l[11] == "\"\"" ? "0" : (maps.ToLookup(p => l[5], p => l[3]) == "Mobile Data" || maps.ToLookup(p => l[5], p => l[3]) == "Mobile SMS") ? "0" : l[11].Replace("\"","").ToString())
};
I am getting error in Calls variable in File001 Linq method
It's not clear what you are trying to achieve, but here is my advice. Now you are working with spitted lines array like this l[0] != "\"Statement Date\"". I think only you know what data should be at index 9. It's not very readable, error-prone (typo in Statemnet Date, wrong index), and it's very hard to maintain. Instead this create an object, which will parse line for you and provide data via strongly typed properties with nice names.
public class ICDEntry
{
public static ICDEntry CreateFrom(string line)
{
string[] values = line.Split(',');
var entry = new ICDEntry();
// assign values to properties:
// if (values[0] == "\"Statement Date\"")
// entry.StatementDate = DateTime.Parse(values[1]);
// entry.IsSomething = values[11] == "\"\""
return entry;
}
public DateTime? StatementDate { get; private set; }
public string MobileSMS { get; private set; }
public bool IsSomething { get; private set; }
}
Now you can parse each line, and then work in strongly typed world making queries to your ICD entries:
var entries = File.ReadLines(ICD_process).Select(l => ICDEntry.CreateFrom(l));
var File001 = from e in entries
where e.StatementDate.HasValue
select new {
Calls = e.IsSomething ? "0" : e.MobileSMS; // use ICDEntry here
};
I have a datagridview in my form. It fills by selecting country with cities of country.I have set the property (AllowUsersToAddRow = True)
but when i run my project user can't add or edit or delete any row.I checked it.It is not readonly(readonly = false) and It is enable (Enabled = true)
What's the problem?
Code of fill datagridview:
private void cmbCountryValues_SelectedIndexChanged(object sender, EventArgs e)
{
dgvCityValues.Enabled = cmbCountryValues.SelectedIndex>=0;
if (!dgvCityValues.Enabled)
{
dgvCityValues.DataSource = null;
return;
}
int CountryId = int.Parse(cmbCountryValues.SelectedValue.ToString());
dgvValues.DataSource = from record in Program.dal.Cities(CountryId) select new { record.City};
}
If you find this question useful don't forgot to vote it.
To give a simplified example, if I do the equivalent of your query, such as:
var cities = new City[] { new City("New York","NY"), new City("Sydney","SY"), new City("London","LN") };
dataGridView.DataSource = cities;
I get the same result as you - no option to add new rows, but if I change to BindingList<T> and set this to AllowNew it all works:
var cities = new City[] { new City("New York","NY"), new City("Sydney","SY"), new City("London","LN") };
var citiesBinding = new BindingList<City>(cities);
citiesBinding.AllowNew = true;
dataGridView.DataSource = citiesBinding;
EDIT - with a solution for your particular example:
private class City
{
public string Name { get; set; }
}
private void cmbCountryValues_SelectedIndexChanged(object sender, EventArgs e)
{
dgvCityValues.Enabled = cmbCountryValues.SelectedIndex >= 0;
if (!dgvCityValues.Enabled)
{
dgvCityValues.DataSource = null;
return;
}
int CountryId = int.Parse(cmbCountryValues.SelectedValue.ToString());
var queryResults = from record in Program.dal.Cities(CountryId) select new City { Name = record.City };
var queryBinding = new BindingList<City>(queryResults.ToList());
queryBinding.AllowNew = true;
dgvValues.DataSource = queryBinding;
}
Note that a) I had to change the anonymous type in the query select into a concrete type City and also change the IEnumerable<T> returned by Linq query to an IList<T> compatible type to create the BindingList<T>. This should work, however :)