How to fetch data to ComboBox from a Linq query? - c#

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
}
}

Related

litedb see results from query

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);
}
}

How to generate a treeview with group format? ( Letter that indicate the starting word )

I am developing an ASP.NET website and have a treeview to display countries which store in a MYSQL DB.
I am using this code to bind the data to treeview.
dt_Record is a datatable.
private void get_Countries()
{
try
{
dt_Record.Clear();
dt_Record = objCommonMethods_Bll.Get_Countries();
if (dt_Record.Rows.Count != 0)
{
foreach (DataRow dr in dt_Record.Rows)
{
TreeNode node = new TreeNode();
node.Text = dr["name"].ToString();
node.Value = dr["Countries_id"].ToString();
tvCountries.Nodes.Add(node);
}
}
}
catch (Exception)
{
throw;
}
}
So it displaying the countries like this
But I want to display countries like this. With a group letter to easily recognise the starting letter which can not be click.
Can I achieve above format? Then how to do that?
Thank you very much.
I have done this using LINQ query but in my case I have user a datastructure for a model instead of from database.
But you can use database in your scenario.
Here is my code:
1) I have created a class to use it as table.
public class Country
{
public string Name { get; set; }
}
2) I have made a List with data filled, & in your case you are getting data from your database.
List<Country> countriesList = new List<Country>()
{
new Country{Name="Algeria"},
new Country{Name="Angola"},
new Country{Name="Benin"},
new Country{Name="Botswana"},
new Country{Name="Burkina Faso"},
new Country{Name="Burundi"},
new Country{Name="Cameroon"},
new Country{Name="Cape Verde"},
};
3) and finally written the LINQ query to get the Grouped data as::
var temp = (from con in countriesList
group con by con.Name[0] into gr
select new
{
Key = gr.Key,
Value = gr.ToList()
}).ToList();

filtered Query for objectContext Using Linq to SQL

i have tried to search some examples about my approach but all questions was not close enough to what i was trying to achieve .
for the TLDR sake , Question is : how do i make it work as in plain sql query?
using c# - Winforms with SqlCompact4 and Linq to SQL
my scenario involves a form with all the relevant Db table columns as availble filters to query
and then on text change event of each filtertextbox as a filter, the datasource of the gridview updates accordingly
and because i allow filtered search via many of them columns i was trying to avoid use of some extra
lines of code.
so lets say we only concentrate on 4 columns
custID, name, email, cellPhone
each has its corresponding TextBox.
i am trying to make a query as follows :
first i systematically collect all Textbox into a List
var AllFormsSearchFiltersTBXLst = new List<TextBox>();
code that collects all tbx on current form
var AllFormsSearchFiltersTBXLst = [currentFormHere].Controls.OfType<TextBox>();
so now i have all of textboxes as filters regardless if they have any value
then check who has some value in it
forech textbox in this filters textboxes if text length is greater than zero
it means that current filter is active
then.. a second list AllFormsACTIVESearchfiltersTBXLst will contain only active filters
what i was trying to achieve was in same way i didn't have to specify each of textbox objects
i just looped through each of them all as a collection and didn't have to specify each via it's id
now i want to make a filter on a dbContext using only those active filters
so i will not have to ask if current tbxName is email
like
query = db.Where(db=>db.email.Contains(TbxEmail.Text));
and again and again for each of 10 to 15 columns
what i have got so far is nothing that implements what i was heading to.
using (SqlCeConnection ClientsConn = new SqlCeConnection(ConfigurationManager.ConnectionStrings["Conn_DB_RCL_CRM2014"].ConnectionString))
{
System.Data.Linq.Table<ContactsClients> db = null;
// get all column names from context
var x =(System.Reflection.MemberInfo[]) typeof(ContactsClients).GetProperties();
using (DB_RCL_CRM2014Context Context = new DB_RCL_CRM2014Context(ClientsConn))
{
if (!Filtered)
db = Context.ContactsClients;//.Where(client => client.Name.Contains("fler"));
else
{
db = Context.ContactsClients;
// filters Dictionary contains the name of textBox and its value
// I've named TBX as Columns names specially so i could equalize it to the columns names when needed to automate
foreach (KeyValuePair<string,string> CurFltrKVP in FiltersDict)
{
foreach (var memberInfo in x)
{
// couldn't find out how to build the query
}
}
}
BindingSource BS_Clients = new BindingSource();
BS_Clients.DataSource = db;
GV_ClientInfo_Search.DataSource = BS_Clients;
what i normally do when working with plain sql is
foreach textbox take its value and add it into a string as filter
var q = "where " ;
foreach(tbx CurTBX in ALLFILTERTBX)
{
q +=CurTBX.Name +" LIKE '%" + CurTBX.Text + "%'";
// and some checking of last element in list off cores
}
then pass this string as a filter to the main select query ... that simple
how do i make it work as in plain sql query?
I think that you're trying to get the property of db dynamically, like: db.email according to the looped name of your textbox (here 'email'). However, I recommend you to do it some other way. I'd make a switch for each type of the property, like: email, name etc. Something like this:
// Create a list for the results
var results = new List<YourDBResultTypeHere>();
foreach(tbx CurTBX in ALLFILTERTBX)
{
switch(CurTBX.Name) {
case "email":
results.AddRange(db.Where(db => db.email.Contains(tbx.Text)).ToList());
break;
case "name":
results.AddRange(db.Where(db => db.name.Contains(tbx.Text)).ToList());
break;
}
}
try this
void UpdateGridViewData(bool Filtered=false, Dictionary<string,string> FiltersDict = null)
{
using (SqlCeConnection ClientsConn = new SqlCeConnection(ConfigurationManager.ConnectionStrings["Conn_DB_RCL_CRM2014"].ConnectionString))
{
System.Data.Linq.Table<ContactsClients> db = null;
IEnumerable<ContactsClients> IDB = null;
BindingSource BS_Clients = new BindingSource();
System.Reflection.MemberInfo[] AllDbTblClientsColumns = (System.Reflection.MemberInfo[])typeof(ContactsClients).GetProperties();
using (DB_RCL_CRM2014Context Context = new DB_RCL_CRM2014Context(ClientsConn))
{
if (!Filtered)
{
db = Context.ContactsClients;
BS_Clients.DataSource = db;
}
else
{
string fltr = "";
var and = "";
if (FiltersDict.Count > 1) and = "AND";
for (int i = 0; i < FiltersDict.Count; i++)
{
KeyValuePair<string, string> CurFltrKVP = FiltersDict.ElementAt(i);
if (i >= FiltersDict.Count-1) and = "";
for (int j = 0; j < AllDbTblClientsColumns.Length; j++)
{
if (AllDbTblClientsColumns[j].Name.Equals(CurFltrKVP.Key))
{
fltr += string.Format("{0} Like '%{1}%' {2} ", AllDbTblClientsColumns[j].Name, CurFltrKVP.Value, and);
}
}
}
try
{
IDB = Context.ExecuteQuery<ContactsClients>(
"SELECT * " +
"FROM ContactsCosmeticsClients " +
"WHERE " + fltr
);
BS_Clients.DataSource = IDB;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
GV_ClientInfo_Search.DataSource = BS_Clients;
}
}
}

Get the insert and update SQL queries from LINQ To Sql data context

I have a LINQ To Sql data context, with a mapping to tables User and Group. A user belongs to a Group.
So I would like to get the corresponding SQL generated for Insert/Update by data context against a particular entity.
For e.g.
using (var context = new TestBedDataContext())
{
using (var trans = new TransactionScope())
{
context.Users.InsertOnSubmit(new User
{
Name = "Test",
Password = "Password",
Username = "test",
Group1 = new Group
{
Name = "Group1"
}
});
// Get the query for User entity
}
}
Here I would like to get the queries that will be generated for inserting a new user along with Group entity.
I know context.Log property can be used to capture the entire SQL generated, the problem with that approach is, it will catch all the SQL which are not in my interests (like change scripts for some other entities)
public void addPatientInformation() {
using(DbClassesDataContext myDb = new DbClassesDataContext()) {
myDb.PatientInfos.InsertOnSubmit(new PatientInfo {
Phy_ID = physcianID,
Pat_First_Name = txtFirstName.Text,
Pat_Middle_Init = txtMiddleName.Text,
Pat_Last_Name = txtLastName.Text,
Pat_Gender = cmbGender.Text,
Pat_Marital_Status = cmbMaritalStatus.Text,
Pat_Date_Of_Birth = dtpDOB.Value,
Pat_Home_Add = txtHomeAdd.Text,
Pat_Home_Num = txtPhone.Text,
Pat_Work_Add = txtWorkAdd.Text,
Pat_Work_Num = txtWorkPhone.Text,
Pat_Prim_Physician = txtPrimPhysician.Text,
Pat_Ref_Physician = txtRefePhysician.Text,
});
myDb.SubmitChanges();
}
}

Comparing Arrays and Create data into database

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.

Categories

Resources