I am new to c#/.net/WPF.
I am trying to fill a combobox with values taken from a database.
The LINQ query gets a list of all companies in the database and the code attempts to fill a ComboBox control with this list.
The C# code below successfully gets the results (I previously outputted it with a MessageBox.Show()).
My Next step was to remove that bit and, instead, put in the code which would fill out this ComboBox:
<ComboBox Name="companyComboBox"/>
The c#:
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.Data.SqlClient;
using System.Data.Linq;
using System.Data.Linq.Mapping;
namespace LeadSystem
{
/// <summary>
/// Interaction logic for NewLead.xaml
/// </summary>
public partial class NewLead : Window
{
public NewLead()
{
// Use a connection string.
DataContext db = new DataContext("Data Source=HP\\SQLEXPRESS;Initial Catalog=LeadSystem;Integrated Security=True");
// Get a typed table to run queries.
Table<Company> Companies = db.GetTable<Company>();
// Attach the log to show generated SQL.
db.Log = Console.Out;
// Query for all companies.
var companyQuery =
from c in Companies
select new { Name = c.CompanyName, ID = c.CompanyID };
companyComboBox.ItemsSource = companyQuery.ToList();
companyComboBox.DisplayMemberPath = "Name";
companyComboBox.SelectedValuePath = "ID";
InitializeComponent();
}
}
}
The problem I keep getting is:
Object reference not set to an instance of an object.
^ it's talking about companyQuery, where I try to use it to fill the comboBox.
I thought this must be because of deferred execution, and so I had a look around the web to find a solution. I've seen several people say to add ToList() at the end of that line of code, but nothing changed.
So, does someone here know what I'm doing wrong??
I have looked around the web (including Stackoverflow) and nothing has helped me fix mine.
Also, if it's not too cheeky to ask two questions in one go... How do I set the selected value and displayed values in my ComboBox? Is it correct, the way I already have it?
Thanks
Try to fill the companyComboBox after the initializeComponent
InitializeComponent();
companyComboBox.ItemsSource = companyQuery.ToList();
companyComboBox.DisplayMemberPath = "Name";
companyComboBox.SelectedValuePath = "ID";
Put InitializeComponent(); before you set the itemSource
Related
I'm using XBim IFC libraries in order to get some info of a Building model elements.
Specifically, of IfcWall entities.
I have to acces Wall Base Quantities (lenght, height, width, etc.) but I cant reach those properties from IfcWall class.
I have this class:
using Dapper;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Xbim.Ifc;
using Xbim.Ifc4.ActorResource;
using Xbim.Ifc4.DateTimeResource;
using Xbim.Ifc4.ExternalReferenceResource;
using Xbim.Ifc4.PresentationOrganizationResource;
using Xbim.Ifc4.GeometricConstraintResource;
using Xbim.Ifc4.GeometricModelResource;
using Xbim.Ifc4.GeometryResource;
using Xbim.Ifc4.Interfaces;
using Xbim.Ifc4.Kernel;
using Xbim.Ifc4.MaterialResource;
using Xbim.Ifc4.MeasureResource;
using Xbim.Ifc4.ProductExtension;
using Xbim.Ifc4.ProfileResource;
using Xbim.Ifc4.PropertyResource;
using Xbim.Ifc4.QuantityResource;
using Xbim.Ifc4.RepresentationResource;
using Xbim.Ifc4.SharedBldgElements;
namespace ProcesadorPremoldeado.IFC
{
public class IFCCalculos
{
public void CalculoPlacas(string fileName, XbimEditorCredentials editor)
{
using (var model = IfcStore.Open(fileName, editor))
{
using (var transaction = model.BeginTransaction("Quick start transaction"))
{
//get all Walls in the model
var ifcWallsList = model.Instances.OfType<IfcWall>();
foreach (var wall in ifcWallsList)
{
var prop = wall.PhysicalSimpleQuantities.Where(x=>x.Name=="Height");
}
transaction.Commit();
}
}
}
}
}
That lambda expression return me a row, correctly filtered by Name parameter, as this property is accessible.
But I cant access the property call "LengthValue", the strange thing is that the property is visible during debbugin if I put a breakpoint, under "prop" list in the foreach loop.
Anyone could give me an idea of what could be happening?
Thanks in advance!
This is because LengthValue is a property of IfcQuantityLength, but PhysicalSimpleQuantities are of supertype IfcPhysicalQuantity. You just need to select quantities of the right type
var height = wall.PhysicalSimpleQuantities
.OfType<IfcQuantityLength>()
.Where(x=>x.Name=="Height")?
.LengthValue;
The 'connection.Query' does not prompt for Dapper using statement. Dapper has been installed several times. I've tried entering the using statement 'using Dapper' but it's underlined in red saying:
Dapper namespace could not be found
Why is it happening?
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
namespace DataAccessLibrary
{
public class SQLDataAccess
{
public List<T> LoadData<T, U>(string sqlStatement, U parameters, string connectionString)
{
using (IDbConnection connection = new SqlConnection(connectionString))
{
List<T> rows = connection.Query<T>(sqlStatement, parameters).ToList();
}
}
}
}
I'm embarrassed to say i installed Dapper into the wrong project in my application. I assumed (never assume, always check) wrongly that the installation would be seen throughout my app.
Problem solved.
I have tried to search for this but every example I find has a problem like them actually having the same namespace as their class or something.
I am simply trying to start using Linq. When I add new item Host is localhost. I have my database in Visualstudio and my project name is different than the DataContext name but I can't get it initialized. I get error:
'LinkedContext' is a namespace but is used like a type'
here is code...
namespace TryAgain
{
class Program
{
static void Main(string[] args)
{
LinkedContext db = new LinkedContext();
}
}
}
LinkedContext doesn't work? In settings of the Database Diagram it says the Entity Namespace is 'LinkedContext' So what am I missing. I thought I saw you could run that one line of code to connect your database that is already in VisualStudio due to adding a new item and then start playing with it? I just want to be able to practice with a database! Do stuff like:
var example = from x in example.Table
orderby x.field
select x;
you need using LinkedContext at the top of your file. the error you’re getting is telling you LinkedContext is a namespace but you’re treating like a type, ie a class. once you define it at the top you can then use the type that you need within that namespace.
added "using LinkedContext" to the top of code then also had to use LinkedDataContext not just LinkedContext:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using LinkedContext;
namespace TryAgain
{
class Program
{
static void Main(string[] args)
{
LinkedDataContext db = new LinkedDataContext();
var example = from x in db.employees
orderby x.employee_id
select x;
foreach (var whatever in example)
{
Console.WriteLine(whatever.name);
}
I am attempting to use Microsoft's Bing Spellcheck API with a WPF application. I have a textbox where I enter in some text, and then a button that checks the spelling in the textbox, and should return the red line underneath anything that is misspelled. I think I have it programmed correctly, but nothing is happening when I click on the button. I am following along with Microsoft's code snippet on how to do this: https://dev.cognitive.microsoft.com/docs/services/56e73033cf5ff80c2008c679/operations/57855119bca1df1c647bc358
I understand that WPF does have a Spellcheck feature available, however I want to practice using some of Microsoft's Cognitive APIs for my own benefit.
Here is my code for my MainWindow.xaml.cs of the WPF application:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Net.Http.Headers;
using System.Net.Http;
using System.Web;
namespace Project1
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
static async void MakeRequest()
{
MainWindow window = new MainWindow();
var client = new HttpClient();
var queryString = HttpUtility.ParseQueryString(string.Empty);
//Request headers
client.DefaultRequestHeaders.Add("Ocp-Apim-Subscription-Key", "e94333d69eb6493d86aaa4b25e42d0d0");
//Request parameters
queryString["text"] = window.TextBox.Text;
var uri = "https://api.cognitive.microsoft.com/bing/v5.0/spellcheck/?" + queryString;
await client.GetAsync(uri);
}
private void Button_Click(object sender, RoutedEventArgs e)
{
MakeRequest();
}
}
}
If anyone is able to help me understand what I am doing wrong, that would be great. I am completely new to using APIs so I am still trying to figure out exactly how to use them. Thanks!
As you mentioned that u don't know how to get the result I will show u an example.
You have to parse the reponse and update your TextBox by yourself.
static async void DownloadPage()
{
var queryString = HttpUtility.ParseQueryString(string.Empty);
queryString["text"] = "Bill Gatas";
queryString["mode"] = "spell";
var uri = "https://api.cognitive.microsoft.com/bing/v5.0/spellcheck/?" + queryString;
using (var client = new HttpClient())
{
client.DefaultRequestHeaders.Add("Ocp-Apim-Subscription-Key", "e94333d69eb6493d86aaa4b25e42d0d0");
using (var response = await client.GetAsync(uri))
{
string result = await response .Content.ReadAsStringAsync(); //Put here a breakpoint
}
}
}
If you put a breakpoint on result you will see that it contains the response (with suggestions) in JSON format.
Ok, so, I created a connection between Visual Studio's C# (2012) and Access. That means, I've done it the manual way (with no code). However, this method can't help me do exactly what I want, so I've done the coding way as well.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.OleDb;
using System.Configuration;
using System.Xml.Serialization;
namespace WindowsFormsApplication1
{
public partial class horaireForm : Form
{
DateTime semSess;
int numSemaine;
int jourSem;
int periode;
string theoOuLabo;
string lesCours;
string cours;
string lesProfs;
string unprof;
string lesLocaux;
string lesGroupes;
string laComm;
string conn = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\\Users\\Stanley\\Desktop\\stuff\\Hiver 2013\\Horaires_EcranA2013.accdb";
(Sorry if it's long). Anyways, after this, I have this code here that gets info from a combobox (each case is the date of the weeks of a college semester). Since apparently I can't select the primary key if it's the values in the combobox, I've decided to use the dates as the values to select in the combobox and then use it to select the actual primary key in the database.
semSess = Convert.ToDateTime(comboSemSess.Text);
OleDbConnection laConn = new OleDbConnection(conn);
try
{
laConn.Open();
laComm = "SELECT NumeroSemaine FROM SemainDelaSession WHERE DebutSemaine = " + semSess;
OleDbCommand myAccessCommand = new OleDbCommand(laComm, laConn);
OleDbDataReader reader = myAccessCommand.ExecuteReader();
while (reader.Read())
{
numSemaine = Convert.ToInt32(reader["NumeroSemaine"]);
}
}
catch
{
MessageBox.Show("Une erreur s'est produite en accédant à la base de données");
}
finally
{
laConn.Close();
}
However, I still can't connect. It still gets the MessageBox. Does it have to do with the fact that I've done another connection before it, or the way I typed the connectionString, because I have no idea.
I can see a few issues... in the While (reader.Read()) block, you're overwriting numSemaine each time so you'll only ever get the last result in the datareader.
Also the date in the SELECT statement should have quotes around it (treat it like a string in SQL) and really it should be parameterised rather than concantenated (hard to SQL Inject from a combo box but not impossible and it's good practise anyway).
Also, a path just needs one \ between directories, not two.