I'm binding an ASP.NET control to the result of a LINQ query. I'd like to HtmlEncode one of the properties of the contained objects before binding to the control, but I want to do it without altering the data because I do a DataContext.SubmitChanges() later on. How can this be done?
Code that won't work:
var ds = (from s in dc.SearchResults
orderby s.datetime descending
select s)
.Take(int.Parse(ConfigurationManager.AppSettings["RecentItemQty"]));
foreach (SearchResult sr in ds)
sr.Query = Server.HtmlEncode(sr.Query);
rSearches.DataSource = ds;
rSearches.DataBind();
Your could encode it when you do your binding...
<asp:YourDataBoundControl>
<ItemTemplate>
Query: <span><%# Server.HtmlEncode((string)Eval("Query")) %></span>
</ItemTemplate>
</asp:YourDataBoundControl>
Dummy me. I just need to HtmlEncode it within the OnItemDataBound() event.
Have two copies of the data:
from s in dc.SearchResults
orderby s.datetime descending
select new {
Original = s,
Encoded = Server.HtmlEncode(s.Query)
};
Or you could use HttpUtility.HtmlEncode('string');
Both are valid but the one above is available anywhere within an application easier than loading up HttpContext.Current.Server.HtmlEncode.
Related
I have several controls that I am trying to bind to LINQ queries but am getting the following error:
$exception {"DataBinding: 'System.Data.DataRow' does not contain a property with the name 'Key'."} System.Exception
{System.Web.HttpException}
I'm binding it the following way:
myDropDownList.DataSource = myDataTable.AsEnumerable().Where(
r => ((string) r["ColumnName"]) == "ColumnIWant").ToList()
myDropDownList.DataTextField = "Key";
myDropDownList.DataValueField = "Value";
I have tried this both with and without the .ToList(), as suggested in other answers but with no effect.
"myDataTable" has both columns "Key" and "Value". It was my understanding you could bind this way, but I seem to be missing a step in specifying the property names.
My suggestion (as it has worked to me this way with GridView and DropDownList controls), is that you specify this DataTextField and DataValueField properties in the design file (aspx) like this:
<asp:DropDownList ID="DropDownList1" runat="server"
DataTextField="Key" DataValueField="Value">
</asp:DropDownList>
This way, you can still apply the ToList() function to the DataTable and it will work (tested).
If if doesn't, maybe you need to set up one break-point after filling up your myDataTable and another one after the LINQ query, to check if the "Key" and "Value" columns are still there.
If it defenitely contains values for key and Value in the data table then i suggest you to use like the following :
myDropDownList.DataSource = myDataTable.AsEnumerable().Where(
r => (r.Field<string>("ColumnName")) == "ColumnIWant").ToList<DataRow>();
myDropDownList.DataTextField = "Key";
myDropDownList.DataValueField = "Value";
I had changed ToList() to .ToList<DataRow>(); so that the datasourse can find the key and value as same as from a datatable, and change the comparison like this: r.Field<string>("ColumnName")
Using .CopyToDataTable() works for what I'm trying to do, but I'd still prefer to know how to bind the data directly to the EnumerableRows collection if that's possible.
Here is what I did:
myDropDownList.DataSource = myDataTable.AsEnumerable().Where(
r => ((string) r["ColumnName"]) == "ColumnIWant").CopyToDataTable();
myDropDownList.DataTextField = "Key";
myDropDownList.DataValueField = "Value";
My solution consists out of a single page, "Content.aspx" which I use to populate with different types of html data depending on the querystring.
I need to know, if possible, how to load aspx content in my page.
I've tried adding code like :
<asp:Label ID="lblName" runat="server"></asp:Label>
But it gets displayed as plain text.
Here is my code that I use to retrieve the data from the database.
string category = Request.QueryString["category"].ToString();
using (MyEntity dbc = new MyEntity())
{
ContentTables cms = (from c in dbc.ContentTable
where c.Name == category && c.Status == true
select c).First();
divHeader.InnerHtml = cms.Header;
divContent.InnerHtml = cms.Content;
if (cms.Header == "dataPage")
{
/*Code Requirement Here*/
}
}
Any help will be greatly appreciated. Thanks
Use StringBuilder and Literal
StringBuilder sb = new StringBuilder();
sb.append("Your Contain From Database");
Literal1.Text = sb.ToString(); //Bind Contain to Litral
The StringBuilder AppendFormat method is useful for generating text based on a pattern.
I am trying to sort some data from entity before passing them to another function. Both tableName and columnName are selected dynamically. This is what I'm doing:
string tableName = cboSelectTable.Text.ToString();
var comboBoxColumn = from a in Context.RULES where
a.ISCOMBOBOXCOLUMN == "Y" select a.COLUMN;
foreach (var colName in comboBoxColumn)
{
var getTableName = entityModel.GetType()
.GetProperty(tableName)
.GetValue(entityModel, null);
var getData = ((IQueryable<object>)getTableName)
.Where(colName + "!=null")
.Select(colName)
.Distinct()
.OrderBy('"'+ colName +'"');
dgvCboColumn(getData, colName);
}
But this is not sorting the data. I also tried some other methods too, but couldn't figure it out. How can I resolve this?
I do not think that is the way, .OrderBy(...) works. Try ordering by an attribute:
SomeList.OrderBy(l => l.SomeAttribute);
I suspect ordering by a string results in each element being ordered by the same attribute, thus not ordering at all. In addition, I am not sure, if your where-clause works like that.
There is another relevant SO question already answered. You might want to have a look at it: click me!
You can simply place the Select after the OrderBy:
var getData = ((IQueryable<object>)getTableName)
.Where(colName + "!=null")
.OrderBy(colName)
.Select(colName)
.Distinct();
This will allow you to reference the column name. (doesn't seem to work for some reason).
Alternatively, you can reference the current instance:
var getData = ((IQueryable<object>)getTableName)
.Where(colName + "!=null")
.Select(colName)
.Distinct()
.OrderBy("it");
I'm fairly new to LINQ (and SQL at that). When trying to query my SQL Database in C# "Supervisors" (which contains only one column "Names" made of nvarchar(50) variables, none of which are Null), supvName ends up being an empty list. If I don't cast it as a List, supvName is of typeSystem.Data.EnumerableRowCollection<string> if that helps.
public addNewEmp()
{
InitializeComponent();
using (TestDataSet db = new TestDataSet())
{
var supvName = (from n in db.Supervisors
select n.Names).ToList();
foreach (string n in supvName)
{
supv_cbox.Items.Add(n);
}
}
}
Even when using a Where statement, that one result doesn't show up, so I'm sure it's something simple in my code that I just can't seem to figure out. I've already tried using AsEnumerable() which didn't change anything.
EDIT: I'm doing this in VS 2010 WPF. Also when I Preview Data in TestDataSet.xsd, it does return the all the data in the Database.
Solution: The problem was when I used a DataSet. When I used a DataContext instead it worked perfectly fine. Thanks to your DataSet or DataContext question lazyberezovsky or I never would have tried that.
Using the following works:
var supvName = db.Supervisors.Select(m => m.Names);
supv_cbox.ItemsSource = supvName;
Thanks Surjah Singh too.
When you are enumerating over DataTable with Linq to DataSet, you should call AsEnumerable() on datatable and use Field<T> extension to get column value:
var supvName = (from r in db.Supervisors.AsEnumerable()
select r.Field<string>("Names")).ToList();
BTW query variable r will be of DataRow type.
Your code can be simplified to:
var names = db.Supervisors.AsEnumerable().Select(r => r.Field<string>("Names"));
supv_cbox.DataSource = names.ToList();
//Var supvName = Supervisors.Select(m=>m.Names);
var supvName = from s in Supervisors.Tables[0].AsEnumerable()
select s.Field<string>("Names");
Situation:
I am attempting to bind a BindingList<string[]> constructed from a LINQ to SQL query to a DataGridView.
Problem:
I either cannot make modification to the DataGridView after items are generated -or- I get a bunch of unwanted fields in my DataGridView (it depends on which iteration of my code I use) I have googled as hard as I can and tried implementing most of the solutions I have found online to no avail.
I know that string has no public property for its actual value. I am having a difficult time determining how to retrieve that (I believe is part of the problem).
C#
int item = (from p in CurrentConversion.Companies[lbCompanies.SelectedIndex].Modules
where p.ModuleName.Equals(clbModules.SelectedItem)
select p.ModuleId)
.FirstOrDefault();
BindingList<string[]> Data = new BindingList<string[]>((
from p in CurrentConversion.Companies[lbCompanies.SelectedIndex].QuestionAnswers
where p[2].Equals(item)
select new string[] { p[0].ToString(), p[3].ToString() })
.ToList());
dgvQuestions.DataSource = Data;
dgvQuestions.Refresh();
Unwanted Behavior:
This occurs after binding
Question:
Why is this happening?
How do I fix it?
Additional Information:
I am not sure what additional information may be need but I will supply what is requested.
Also if I switch to my other code iteration:
int item = (from p in CurrentConversion.Companies[lbCompanies.SelectedIndex].Modules where p.ModuleName.Equals(clbModules.SelectedItem) select p.ModuleId).FirstOrDefault();
var Data = new BindingList<object>((from p in CurrentConversion.Companies[lbCompanies.SelectedIndex].QuestionAnswers where p[2].Equals(item) select new {Question = p[0].ToString(), Answer = p[3].ToString() }).Cast<object>().ToList());
dgvQuestions.DataSource = Data;
dgvQuestions.Refresh();
dgvQuestions.Columns[1].ReadOnly = false;
I can see the data properly but I cannot edit the column I would like to.
You are binding to a list of string arrays, and you are getting the properties form the array. Most likely you want something like the following:
var Data = new BindingList<object>((
from p in CurrentConversion.Companies[lbCompanies.SelectedIndex].QuestionAnswers
where p[2].Equals(item)
select new {
Val1 = p[0].ToString(),
Val2 = p[3].ToString()
}).ToList());
The reason you're seeing those fields in the Grid is that you're binding each row to a string[]. So it is automatically displaying the properties of string[] as the columns. There is no built-in logic for the grid to parse an array and use the contents of the array as columns.
In order to get the DataGrid to display your data correctly, you should bind it to a custom type, and it will use the public properties of the type as columns.