System.Data.EvaluateException: 'Cannot find column [NameID].' - visual-studio

I wanted to use a search textbox to filter a datagridview in Visual Studio, where you will enter a certain primary key (i.e. NameID) to filter the results in the datagridview. It throws the error which is noted in the title.
I have tried changing the code from NameID to [NameID] but this action did not work.
private void TxtNamecSearch_TextChanged(object sender, EventArgs e)
{
DataView dtvNames = new DataView(dtNames);
dtvNames.RowFilter = string.Format("Convert
(NameID,'System.String') Like '%{0}%'", TxtNameSearch.Text); //
Errror occurs on this line
NameDataGridView.DataSource = dtvNames;
}
I expect to type in the textbox, the primary key [NameID] which is a numeric number and the results in the datagridview will automatically filter by the column "NameID"

I have not added the DataColumn named NameID to my DataTable, as this column name "NameID" is being retrieved from MySQL database and it is populated into the Datagridview.
As a result, I had to change the code and this code, below, now works fine: -
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading.Tasks;
public class Form1
{
private BindingSource NameBindingSource;
private void Form1_Load(System.Object sender, System.EventArgs e)
{
// Create a new DataTable
DataTable dtName = new DataTable();
// Add the NameID column
dtName.Columns.Add(new DataColumn("NameID"));
// Create a new BindingSource
NameBindingSource = new BindingSource();
// Bind the DataTable to the BindingSource
NameBindingSource.DataSource = dtName;
// Bind the BindingSource to the DataGridView
NameDataGridView.DataSource = NameBindingSource;
}
private void TxtNameSearch_TextChanged(System.Object sender, System.EventArgs e)
{
// Set the filter
NameBindingSource.Filter = string.Format("Convert
(NameID, 'System.String') LIKE '%{0}%'", TxtNameSearch.Text);
}
}

Related

Scrape a table using ScrapySharp and HtmlAgilityPack

I am trying to scrape an economic calendar from a specific website. Actually, I tried many times without any success, I don't know where I am wrong. Can you help me, pls?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using HtmlAgilityPack;
using ScrapySharp.Extensions;
using ScrapySharp.Network;
namespace Calendar
{
class Program
{
static void Main(string[] args)
{
var url = "https://www.fxstreet.com/economic-calendar";
var webGet = new HtmlWeb();
if (webGet.Load(url) is HtmlDocument document)
{
var nodes = document.DocumentNode.CssSelect("#fxst-calendartable tbody").ToList();
foreach (var node in nodes)
{
// event_time
Debug.Print(node.CssSelect("div div").Single().InnerText);
// event-title
Debug.Print(node.CssSelect("div a").Single().InnerText);
}
}
Console.WriteLine("");
Console.ReadLine()
}
}
}
What error are you getting?
If you want to publish the event names and times from the website, I am assuming you need to read the table.
You can do so using
HtmlNode tablebody = doc.DocumentNode.SelectSingleNode("//table[#class='fxs_c_table']/tbody");
foreach(HtmlNode tr in tablebody.SelectNodes("./tr[#class='fxs_c_row']"))
{
Console.WriteLine("\nTableRow: ");
foreach(HtmlNode td in tr.SelectNodes("./td"))
{
Console.WriteLine(td.SelectSingleNode("./span").InnerText);
}
}
Get hold of the table with the class attribute and then use relevant XPATH to traverse the elements. Please post the error you are getting with your code.

Dynamically generated columns in radgrid disappear after postback

Am using radgrid and creating it in aspx but on certain action i add more GridTemplateColumns to the grid.
private void CreateDateColumns(List<DateTime> occurenceList)
{
if (occurenceList != null && occurenceList.Count > 0)
{
int index = 1;
foreach (DateTime occurence in occurenceList)
{
string templateColumnName = occurence.Date.ToShortDateString();
GridTemplateColumn templateColumn = new GridTemplateColumn();
templateColumn.ItemTemplate = new MyTemplate(templateColumnName, index);
grdStudentAttendanceList.MasterTableView.Columns.Add(templateColumn);
templateColumn.HeaderText = templateColumnName;
templateColumn.UniqueName = templateColumnName;
index++;
}
}
}
private class MyTemplate : ITemplate
{
protected RadComboBox rcbAttendance;
private string colname;
private int _index;
public MyTemplate(string cName, int index)
{
colname = cName;
_index = index;
}
public void InstantiateIn(System.Web.UI.Control container)
{
rcbAttendance = new RadComboBox();
rcbAttendance.Items.Add(new RadComboBoxItem("---Select---", "-1"));
rcbAttendance.Items.Add(new RadComboBoxItem("Present", "1"));
rcbAttendance.Items.Add(new RadComboBoxItem("Absent", "2"));
rcbAttendance.Items.Add(new RadComboBoxItem("Leave", "3"));
rcbAttendance.ID = "rcbAttendance" + _index;
container.Controls.Add(rcbAttendance);
}
}
All are fine with creation but when i press save button or any combobox make postback the only dynamically generated columns content disappear and the other columns stay.
What i noticed that columns still in place with headertext but only content are disappeared (in my case content are comboboxes)
After enabling viewstate for grid only header text appear.
What should i do to keep columns contents after postback and get their values ?
When creating template columns programmatically, the grid must be generated completely in the code-behind using the Page_Init event. Then, you must create the templates dynamically in the code-behind and assign them to the ItemTemplate and EditItemTemplate properties of the column. To create a template dynamically, you must define a custom class that implements the ITemplate interface. Then you can assign an instance of this class to the ItemTemplate or EditTemplateTemplate property of the GridTemplateColumn object.
Blockquote
Column templates must be added in the Page_Init event handler, so that the template controls can be added to the ViewState.
Blockquote
Source: Telerik
Basicly, you need to create all GridTemplateColumns in the Page_Init. We had the same problem and this approach fixed it.

ObjectStateEntry GetModifiedProperties() incorrectly detects change to byte[] property

Does Entity Framework incorrectly detect changes to images?
I have a "Person" entity class defined as follows;
public class Person
{
public int Id { get; set; }
public byte[] Photo { get; set; }
}
I have bound the Photo to a PictureBox control on my form using a datasource.
There form also uses a dynamically created bindingNavigator.
I also have written an audit log to populate captured changes
The procedure calls the ObjectContext DetectChanges() and then
var entries = ObjectContext.ObjectStateManager.GetObjectStateEntries()
Which contains an entry showing that the Photo has been modified.
entry.OriginalValues[name] matches entry.CurrentValues[name]
The Column is varbinary(MAX) in SQL Server and the size of the picture files I have loaded are under 1Mb
If I set all of the columns to null the error no longer occurs
The code I use to get the file is
private void LoadPhotoButton_Click(object sender, EventArgs e)
{
using (var dlg = new OpenFileDialog())
{
dlg.Filter = "JPEG files |*.jpg";
if (dlg.ShowDialog() == DialogResult.OK)
{
PhotoPictureBox.Image = Image.FromFile(dlg.FileName);
}
}
}
I note here that hex zero can be inserted as padding characters when these fields are involved in string conversion.... could the binding be doing that somehow?
If I delete the picturebox from the form, or even bind the control as a text box instead of a picturebox then the behaviour is correct ( not that a picture bound to a text box is any use )
I am able to work around the problem by not binding directly to the picture box.
Instead I just load it on the BindingSource_CurrentChanged event using
private void BindingSource_CurrentChanged(object sender, EventArgs e)
{
var obj = (Person) BindingSource.Current;
this.PictureBox.Image = byteArrayToImage( obj.Photo);
}
public Image byteArrayToImage(byte[] byteArrayIn)
{
MemoryStream ms = new MemoryStream(byteArrayIn);
Image returnImage = Image.FromStream(ms);
return returnImage;
}
I am using my work around - documented at the end of the question as a make do answer.

MVC3 LINQ SubmitChanges Invalid

In the method below db.SubmitChanges is shown as invalid/not recognized by intellisense.
This is my first attempt to update records in a database using LINQ and the method may contain other logic/syntactical errors that I havent yet uncovered as well. What is causing the SubmitChanges to be incorrect?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.ComponentModel.DataAnnotations;
using System.Linq.Expressions;
public void updateInfo(RefillViewModel _myRefillViewModel) {
try {
decimal patid = _myRefillViewModel.Patient.Patient_ID;
decimal rxid = _myRefillViewModel.Rx.Rx_ID;
CAHODEntities db = new CAHODEntities();
List<Fill> FillList = db.Fills.Where(p => p.Rx.Rx_ID == rxid && p.Rx.Patient_ID == patid && p.Status == "UnFilled").ToList();
foreach (var item in FillList)
{
if (FillList.Count() == 0)
{
item.Status = "Requested";
}
}
db.SubmitChanges();
}
}
Are you using EF? Because in Entity Framework it's SaveChanges() not SubmitChanges().

Update CRM 2011 using OrganizationServiceContext

How do you update records in CRM 2011 using OrganizationServiceContext? Can anyone provide a simple example? Thanks!
This is my code:
using System.Collections.Generic;
using System.Linq;
using System.ServiceModel.Description;
using Microsoft.Xrm.Sdk.Client;
using Microsoft.Xrm.Client;
using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Linq;
using Microsoft.Xrm.Sdk.Messages;
using Microsoft.Xrm.Client.Services;
using System.Data.Services;
using System.Text.RegularExpressions;
using System.Web.UI.HtmlControls;
using System.Diagnostics;
using System.Web.Security;
using System.Data;
using System.Collections.Specialized;
using System.Web.SessionState;
using System;
using System.Web.Profile;
using System.Configuration;
using System.Web.UI.WebControls;
using System.Collections;
using System.Web.UI.WebControls.WebParts;
using System.Web;
using System.Web.UI;
using System.Drawing;
using System.Text;
using System.Web.Caching;
using Telerik.Web.UI;
using Microsoft.Xrm.Sdk.Discovery;
using Microsoft.Data.Entity;
using System.Data.Entity;
public partial class LeadShareEditPanel : System.Web.UI.UserControl
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void imgBtnSaveNote_Click(object sender, ImageClickEventArgs e)
{
Uri organizationUri = new Uri("http://server/CRMT/XRMServices/2011/Organization.svc");
Uri homeRealmUri = null;
ClientCredentials credentials = new ClientCredentials();
credentials.Windows.ClientCredential = new System.Net.NetworkCredential("user", "password", "domain");
OrganizationServiceProxy orgProxy = new OrganizationServiceProxy(organizationUri, homeRealmUri, credentials, null);
// Get the IOrganizationService
//Get OrganizationServiceContext -the organization service context class implements the IQueryable interface and
//a .NET Language-Integrated Query (LINQ) query provider so we can write LINQ queries against Microsoft Dynamics CRM data.
using (var service = new OrganizationService(orgProxy))
using (var context = new CrmOrganizationServiceContext(service))
{
var contact = context.CreateQuery<Contact>().First(c => c.FirstName == "Bob");
contact.JobTitle = "Developer";
context.UpdateObject(contact);
context.SaveChanges();
contact.EMailAddress1 = "bob#contoso.com";
context.UpdateObject(contact);
context.SaveChanges();
}
}
}
This is an example from the 5.05 SDK help file
using (var service = new OrganizationService(connection))
using (var context = new CrmOrganizationServiceContext(service))
{
var contact = context.CreateQuery<Contact>().First(c => c.FirstName == "Bob");
contact.JobTitle = "Developer";
context.UpdateObject(contact);
context.SaveChanges();
contact.EMailAddress1 = "bob#contoso.com";
context.UpdateObject(contact);
context.SaveChanges();
}
If you haven't already you can download the SDK from here crm 2011 sdk . I would highly reccomend it as it has lots of great samples. The current version is 5.06.
Hope that helps.

Resources