I have drop down and grid view..i fill drop down from database like this
There is two table tblReg and tblRes both have RegionID
protected void Page_Load(object sender, EventArgs e)
{
T1 tea = new T1();
var list1 = tea.tblReg.ToList();
var list = (from ta in list1
let data = ta.Region + " " + ta.StartDate ?? DateTime.Now.ToString() + " " + ta.EndDate ?? DateTime.Now.ToString()
select new { data, ta.RegionID }).ToList();
if(!Page.IsPostBack)
{
regiondrop.DataSource = list;
regiondrop.DataTextField = "data";
regiondrop.DataValueField = "RegionID";
regiondrop.DataBind();
}
}
now there is several values in drop down and i want when i select value from drop down then again to this value data will be display
On dropdown SelectedIndexChange i done this
protected void regiondrop_SelectedIndexChanged(object sender, EventArgs e)
{
T1 ts = new T1();
var dq=(from dropdwn in ts.tblRes
where dropdwn.RegionID==Convert.ToInt32(regiondrop.SelectedValue)
orderby dropdwn.OwnerName
select new {
FFID = dropdwn.FFID,
OwnerName = dropdwn.OwnerName,
RegNo = dropdwn.RegNo,
RegionID = dropdwn.RegionID,
});
GridView1.DataSource = dq;
GridView1.DataBind();
}
when i select value from dropdown it shows error
LINQ to Entities does not recognize the method 'Int32 ToInt32(System.String)' method, and this method cannot be translated into a store expression.
on
GridView1.DataBind();
any solution
Well, as your error mentions, you can't do
Convert.ToInt32(regiondrop.SelectedValue)
in a linq to entities query (it can't be translated in sql / a store expression)
So just change these lines
var dq=(from dropdwn in ts.tblRes
where dropdwn.RegionID==Convert.ToInt32(regiondrop.SelectedValue)
to
var selectedValue = Convert.ToInt32(regiondrop.SelectedValue);
var dq=(from dropdwn in ts.tblRes
where dropdwn.RegionID==selectedValue
You could also do (but the previous solution is more readable)
var dq=(from dropdwn in ts.tblRes
where SqlFunctions.StringConvert((double)dropdwn.RegionID)==regiondrop.SelectedValue
There's a method in SqlFunctions to convert a numeric to a string, but... not a string to a numeric value.
Related
I need to get a value from another column based on the selected item of a drop down list.
So I have a table with 3 values which are:
countryID
countryDescription
countryAbbreviature
and I have a dropdownlist that I fill like:
public void fillCountry() {
//Fills the list with the countries in the database
List<Country> countryList = countryService.getCountries();
ddlCountry.DataSource = countryList;
ddlCountry.DataTextField = "countryDesc";
ddlCountry.DataValueField = "countryID";
ddlCountry.DataBind();
}
What I need is that when the user select like Afghanistan its abbreviature is AF so I need the abbreviature stored on a variable but what I found so far on the sites are dropdowns with only 2 values always like the one I did above.
Assuming your table is named Countries:
var yourSelectedId = YourDropDownList.SelectedValue.ToString();
string yourVariable = dbContext.Countries.Where(x => x.countryID == yourSelectedId).FirstOrDefault().countryAbbreviature;
No straight way to do this, but here is a workaround.
Concatenate abreviation with Id to set as DataValueField of dropdown:
public void fillCountry()
{
//Fills the list with the countries in the database
List<Country> countryList = countryService.getCountries();
var dataSource = countryList.Select(c=> new { DataValueField =
c.countryID + "~" + c.countryAbbreviature, DataTextField = c.countryDesc }).ToList();
ddlCountry.DataSource = dataSource;
ddlCountry.DataTextField = "DataTextField";
ddlCountry.DataValueField = "DataValueField";
ddlCountry.DataBind();
}
on server side maybe in a button click event split them by separator and get Id as well as abreviation:
protected void Button1_Click(object sender, EventArgs e)
{
string selectedValue=ddlCountry.SelectedValue;
int id = int.Parse(selectedValue.Split('~').First());
string abreviation=selectedValue.Split('~').Last();
}
I have a text box which I manage its text changing event to filter the RadGrid:
private void txtJob_TextChanging(object sender, TextChangingEventArgs e)
{
this.gridCustomers.Columns["JobColumn"].FilterDescriptor = new FilterDescriptor
{
Operator = FilterOperator.Contains,
Value = txtJob.Text
};
}
I change JobColumn Text using CellFormatting Event:
private void gridCustomers_CellFormatting(object sender, CellFormattingEventArgs e)
{
if (e.Column.Name == "JobColumn")
e.CellElement.Text = db.tblJobs.First(x => x.JobID == Convert.ToInt32(e.Row.Cells[9].Value.ToString())).JobName;
}
I'm replacing Job ID with its Job Name in JobColumn, in that Text Box which I filtering RadGrid I'm searching for Job Name which is visible in RadGrid Now, but it will filter based on Job ID which is the default value before replacing.
So How can I filter a RadGrid Column based on its Text not Value?
For more information I'm binding a table like this to my girdview:
int JobID
nvarchar(10) Name
nvarchar(100) Address
.
.
.
And I have a table named Jobs like this:
int JobID
nvarchar(30) JobName
.
.
.
I need to get JobID from table one and in data binding (cell Formatting) replace the ID with its JobName in Jobs table.
Why I'm not selecting new and joining two table? because in that case I have not a grid view which can be edited easily, I must use Virtual Gird which is not my goal.
You are trying to hack the system. The correct approach in your case is to use GridVieWComboBoxColumn, which can be bound and DisplayMember and ValueMember to be specified. It also has FilterMode property to determine which field to use for filtering.
Read more GridViewComboBoxColumn | Telerik UI for WinForms Documentation
UPDATE
Here is a sample to get you started
protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);
DataTable mainTable = new DataTable();
mainTable.Columns.Add("JobID", typeof(int));
mainTable.Columns.Add("Name");
mainTable.Columns.Add("Address");
Random rand = new Random();
for (int i = 0; i < 10; i++)
{
mainTable.Rows.Add(rand.Next(1,4), "Name " + i, "Address " + i);
}
DataTable jobsTable = new DataTable();
jobsTable.Columns.Add("JobID", typeof(int));
jobsTable.Columns.Add("JobName");
jobsTable.Rows.Add(1, "ABC ");
jobsTable.Rows.Add(2, "DFG");
jobsTable.Rows.Add(3, "XCV");
radGridView1 = new RadGridView() { Dock = DockStyle.Fill, AutoSizeColumnsMode = GridViewAutoSizeColumnsMode.Fill };
this.Controls.Add(radGridView1);
radGridView1.EnableFiltering = true;
radGridView1.DataSource = mainTable; //this will create all columns
radGridView1.Columns.Remove(radGridView1.Columns["JobId"]);
GridViewComboBoxColumn comboCol = new GridViewComboBoxColumn();
comboCol.DataSource = jobsTable;
comboCol.FieldName = "JobID"; //the name of the field in the main table to look for
comboCol.DisplayMember = "JobName"; //you want to see job names not ids
comboCol.ValueMember = "JobID";
comboCol.FilteringMode = GridViewFilteringMode.DisplayMember;
radGridView1.Columns.Insert(0, comboCol);
}
private void radButton1_Click(object sender, EventArgs e)
{
radGridView1.Columns["JobID"].FilterDescriptor = new FilterDescriptor
{
Operator = FilterOperator.Contains,
Value = "B"
};
}
In the following code, when I click on the button, it will show all the records in the User table instead on giving me a single one which has (UserID == 17).
ReGdbEntities re = new ReGdbEntities();
private void buttonX1_Click(object sender, EventArgs e)
{
Report report = new Report();
string fileName = Application.StartupPath + #"\Reports\Untitled.frx";
var jfja = re.Users.Where(u => u.UserID == 17);
report.RegisterData(jfja.ToList(), "User");
report.GetDataSource("User").Enabled = true;
report.Load(fileName);
report.Prepare();
report.Preview = this.previewControl1;
report.Show();
}
There should be more than one record in the table with the same ID 17 in your database.
If you need only the first record of the search result then you can use FirstOrDefault method.
var jfja = re.Users.Where(u => u.UserID == 17).FirstOrDefault();
I am working with a local database from the following link.
http://www.c-sharpcorner.com/UploadFile/ae35ca/working-with-creating-a-local-database-in-wp7/
Everything is working fine, but i cant fetch the item which age=15
public IList<Employee> GetEmployeeList()
{
IList<Employee> EmployeeList = null;
using (EmployeeDataContext Empdb = new EmployeeDataContext(strConnectionString)
{
IQueryable<Employee> EmpQuery = from Emp in Empdb.Employees select Emp;
EmployeeList = EmpQuery.ToList();
}
return EmployeeList;
}
private void button4_Click(object sender, RoutedEventArgs e)
{
IList<Employee> EmployeesList = this.GetEmployeeList();
StringBuilder strBuilder = new StringBuilder();
strBuilder.AppendLine("Employee Details");
foreach (Employee emp in EmployeesList)
{
strBuilder.AppendLine("Name - " + emp.EmployeeName + " Age - " + emp.EmployeeAge);
}
MessageBox.Show(strBuilder.ToString());
}
The above code fetch all records. But i need a query to fetch items only with age 15.
It should just be a simple case of adding a where clause to your LINQ statement, so something like:
var EmpQuery = from Emp in Empdb.Employees where emp.EmployeeAge == 15 select Emp;
LINQ is lazy. It will only perform an actual DB fetch when it must.
When you call .ToList on an IQueryable you are forcing the DB to enumerate the results and thus fetching all the data from the database.
If you want the database to filter the results rather than the client - return an IQueryable from the GetEmployeeList method and filter that on the button click:
public IQueryable<Employee> GetEmployeeList()
{
// the database should be available on the class here, don't dispose it
// or this won't work since it'll be disposed before you make a query
return (from Emp in Empdb.Employees select Emp);
}
private void button4_Click(object sender, RoutedEventArgs e)
{
var EmployeesList = this.GetEmployeeList();
StringBuilder strBuilder = new StringBuilder();
strBuilder.AppendLine("Employee Details");
// now we can filter it
foreach (Employee emp in EmployeesList.Where(e => e.EmployeeAge == 15))
{
strBuilder.AppendLine("Name - " + emp.EmployeeName + " Age - " + emp.EmployeeAge);
}
// this could also be nicer with string.Join
MessageBox.Show(strBuilder.ToString());
}
I encountered some problem whereby when the user selects the selected name inside the combo box, the data linked with the names selected will show out in the list box. I have problem making into this method. The error falls here.
int selectLocStation = Convert.ToInt32(cbLocStation.SelectedValue);
Error: Unable to cast object of type'<>f_AnonymousType2'2 [System.String.System.Int32]'to type 'System.IConvertible'.
private void cbLocStation_SelectedIndexChanged(object sender, EventArgs e)
{
using (satsEntities Setupctx = new satsEntities())
{
int selectLocStation = Convert.ToInt32(cbLocStation.SelectedValue);
var query = (from db in Setupctx.requiredtimings
join timing t in Setupctx.timings on db.RequiredTimingID equals t.TimingID
where db.RequiredLocationStationID == selectLocStation
select new
{
t.Time2
}).ToList();
List<TimeSpan> lstSelectedTime = new List<TimeSpan>();
foreach (var a in query)
{
lstSelectedTime.Add((TimeSpan)a.Time2);
}
lstTime.DataSource = lstSelectedTime;
}
}
This is what I do to store data inside the combo box.
using (satsEntities Setupctx = new satsEntities())
{
var DeleteRT = (from DelRT in Setupctx.requiredtimings
join locationstationname ls in Setupctx.locationstationnames on DelRT.RequiredLocationStationID equals ls.locationstationID
select new { ls.locStatname, DelRT.RequiredLocationStationID }).Distinct().ToList();
cbLocStation.DataSource = DeleteRT.ToList();
cbLocStation.DisplayMember = "locStatname";
cbLocStation.ValueMember = "RequiredLocationStationID";
Any help will be greatly appreciated.
private void Edit_TS_Load(object sender, EventArgs e)
{
using (satsEntities Setupctx = new satsEntities())
{
var DeleteRT = (from DelRT in Setupctx.requiredtimings
join locationstationname ls in Setupctx.locationstationnames on DelRT.RequiredLocationStationID equals ls.locationstationID
select new {ls.locStatname, DelRT.RequiredLocationStationID}).Distinct().ToList();
cbLocStation.DataSource = DeleteRT.ToList();
cbLocStation.DisplayMember = "locStatname";
cbLocStation.ValueMember = "RequiredLocationStationID";
}
}
Answer is here!
you are trying to convert the anonymous type from the query into timespan which is not possible since it doesn't implement the IConvertible. you can write a wrapper class and select that class in the query.
var query = (from db in Setupctx.requiredtimings
join timing t in Setupctx.timings on db.RequiredTimingID equals t.TimingID
where db.RequiredLocationStationID == selectLocStation
select new WrapperClass
{
Time = t.Time2
}).ToList();
public class WrapperClass
{
public DateTime Time { get; set; }
}
where time is a DateTime you have defined in the wrapper class
if to string is available I would try this
int selectLocStation = Convert.ToInt32(cbLocStation.SelectedValue.ToString());
or this
int selectLocStation =Int32.Parse(cbLocStation.SelectedValue.ToString());
you can also try this
DataRowView drow = (DataRowView)cbLocStation.SelectedItem;
string str = drow.Row.ItemArray[0].ToString();
check if string has numbers and the convert it to int
you can also add databind
BindingContext oBC = new BindingContext();
cbLocStation.BindingContext = oBC;
cbLocStation.DataBindings.Add(new Binding("SelectedValue", DeleteRT, "RequiredLocationStationID", false, DataSourceUpdateMode.OnPropertyChanged));