Confused about Linq query - asp.net

I have created a simple db named Hospital and I have a few columns .I have filled first dropdown named drdoctors.And it works
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack) {
fetchDoctors();
}
}
void fetchDoctors() {
HospitalEntities entitiy = new HospitalEntities();
List<Doctor> doc = entitiy.Doctors.ToList();
drDoctor.DataSource = doc;
drDoctor.DataTextField = "Name";
drDoctor.DataValueField = "DoctorNo";
drDoctor.DataBind();
}
What I want to do is fill the other dropdown with the this doctor's patients .
protected void drDoctor_SelectedIndexChanged(object sender, EventArgs e)
{
int id= Int32.Parse( drDoctor.SelectedValue);
HospitalEntities entities = new HospitalEntities();
var query= from p in entities.Doctors
}
But linq queries are so complicated.How can i do this

This should about do it. Please note, this code wasn't tested and may contain minor errors.
protected void drDoctor_SelectedIndexChanged(object sender, EventArgs e)
{
int id= Int32.Parse( drDoctor.SelectedValue);
HospitalEntities entities = new HospitalEntities();
var query= (from d in entities.Doctors
join m in entities.MedExams on d.DoctorNo equals p.DoctorNo
join p in entities.Patients on m.PatientNo equals p.PatientNo
where d.DoctorNo == id
select p).ToList();
//Populate Patients from query
}

Looking at your diagram, it looks you don't have foreign key relationships set up. I would highly recommend doing this (for uncountable reasons). But by doing this, you will be able to "join" on tables much more easily like this:
protected void drDoctor_SelectedIndexChanged(object sender, EventArgs e)
{
int id = Int32.Parse(drDoctor.SelectedValue);
HospitalEntities entities = new HospitalEntities();
drDoctor.DataSource = entities.Doctors
.Where(x => x.DoctorNo == id)
.SelectMany(x => s.MedExams.Select(y => y.Patients));
drDoctor.DataBind();
}

Related

ASP.Net Fill GridView with Entity Framework Code First

This is my page
Profiles pp;
Tasks t;
protected void Page_Load(object sender, EventArgs e)
{
if (Session["User"] != null)
{
pp = (Profiles)Session["User"];
}
else
{
Response.Redirect("PageLogin.aspx");
}
}
private void data()
{
DBCOntext db= new DBCOntext ();
var manager= db.Tasks.Where(p => p.Personnel == pp.Username).Select(q => q.Manager).FirstOrDefault();
}
I took the data with data class. But I didn't fill gridview. How do I fill gridview? pls help.
Where are you data binding the gridview? You aren't using the manger variable anywhere that I can see.
GridView.DataSource = manager;
GridView.DataBind();

how could i collect all the radio button that chosen in submit button?

Here is my Code:
public partial class Play : System.Web.UI.UserControl
{
int surveyId = 153;
protected void Page_Load(object sender, EventArgs e)
{
// surveyId = int.Parse(Request[SurveyContext.SurveyID]);
FillQuestion();
}
void FillQuestion()
{
IList<Eskadenia.Framework.Survey.Entitis.Question> QuestionLst = Eskadenia.Framework.Survey.Data.QuestionManager.GetQuestionBySurveyId(surveyId);
try
{
RepPlay.DataSource = QuestionLst;
RepPlay.DataBind();
}
catch (Exception ex)
{
Response.Write(ex.InnerException);
}
}
protected void RepPlay_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
RadioButtonList rblAnswers = ((RadioButtonList)e.Item.FindControl("rblAnswers"));
IList<Eskadenia.Framework.Survey.Entitis.Answer> answerlst;
answerlst = Eskadenia.Framework.Survey.Data.AnswerManager.GetAnswerByQuestionID(((Eskadenia.Framework.Survey.Entitis.Question)(e.Item.DataItem)).ID);
for (int i = 0; i < answerlst.Count; i++)
{
rblAnswers.Items.Add(new ListItem(answerlst[i].Name, answerlst[i].ID.ToString()));
}
}
protected void btnSubmit_Click(object sender, EventArgs e)
{
Response.Redirect("~/Surveys.aspx");
}
}
First: you should databind the repeater only if(!IsPostBack):
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
FillQuestion();
}
Otherwise all changes are lost and events aren't triggered.
According to the core issue how to get all selected ListItems in the repeater, is this helpful:
var allSelectedItems = RepPlay.Items.Cast<RepeaterItem>()
.Select(ri => new{
ItemIndex = ri.ItemIndex,
SelectedItem = ((RadioButtonList) ri.FindControl("rblAnswers"))
.Items.Cast<ListItem>()
.First(li => li.Selected)
});
This presumes that you want the ItemIndex as identifier, if you need the ID you have to tell us where it's stored. You could also use ri.FindControl("HiddenIDControl") to get it.
Since you have commented that you want a dictionary, you could use this query:
Dictionary<int, string> questionAnswers = RepPlay.Items.Cast<RepeaterItem>()
.ToDictionary(ri => ri.ItemIndex, ri => ((RadioButtonList)ri.FindControl("rblAnswers"))
.Items.Cast<ListItem>()
.First(li => li.Selected).Value);
Here is the same without LINQ, you're right, in this case the loop is even simpler:
Dictionary<int, string> questionAnswers = new Dictionary<int, string>();
foreach (RepeaterItem item in RepPlay.Items)
{
string selectedValue = ((RadioButtonList)item.FindControl("rblAnswers")).SelectedValue;
questionAnswers.Add(item.ItemIndex, selectedValue);
}
I have noticed that my LINQ approaches were too complicated anyway, you can always use RadioButtonList.SelectedValue since a RadioButtonList doesn't support multi-selection.

DateTime is not recognized

FormatException was unhandled by user code.
The string was not recognized as a valid DateTime.
protected void Page_Load(object sender, EventArgs e)
{
// to simulate a database query
socialEvents = new DataTable();
socialEvents.Columns.Add(new DataColumn("Date", typeof(DateTime)));
socialEvents.Columns.Add(new DataColumn("Description", typeof(string)));
socialEvents.Columns.Add(new DataColumn("Url", typeof(string)));
DataRow row;
row = socialEvents.NewRow();
row["Date"] = DateTime.Now.AddDays(-5);
row["Description"] = "Work";
row["Url"] = "http://www.url.cz";
socialEvents.Rows.Add(row);
}
Error in the following methode:
protected void Calendar1_DayRender(object sender, DayRenderEventArgs e)
{
**DataRow[] rows = socialEvents.Select(
String.Format(
"Date >= #{0}# AND Date < #{1}#",
e.Day.Date.ToShortDateString(),
e.Day.Date.AddDays(1).ToShortDateString()**
)
);
I suggest to use LINQ to do this:
protected void Calendar1_DayRender(object sender, DayRenderEventArgs e)
{
var rows = socialEvents.Rows.Cast<DataRow>
.Where(r => (DateTime)r["Date"] >= e.Day.Date
&& (DateTime)r["Date"] <= e.Day.Date.AddDays(1))
.ToArray();
);
There is no more hassle with string formatted queries: you can use a filter based on real values.
Of course, if Date can be null, you will have to handle this. Just tell and I will edit this code if needed.

Linq deferred execution in asp.net

My dbml contains a master table "M" and a detail table "D1".
My aspx page consists of a TextBox to show M data and a grid to populate with D1 data. I want the grid to populate when a button is clicked to save loading time (D1 contains a lot of rows).
Question 1: Is the following code the correct way to do it?
protected void Page_Load(object sender, EventArgs e)
{
MyDataContext context = new MyDataContext();
M m = context.Ms.Single(n => n.id == id); // id is somehow provided
TextBox1.Text = m.field1;
}
protected void Button1_Click(object sender, EventArgs e)
{
MyDataContext context = new MyDataContext();
M m = context.Ms.Single(n => n.id == id); // id is somehow provided
Grid1.DataSource = m.D1s;
Grid1.DataBind();
}
Question 2: Since I can access m.D1s in Page_Load does this mean the detail data is already fetched from the database anyway or does deferred execution apply?
Unless you explicitly load the children, they will be deferred loaded. If in question, try attaching a profiler to your requests and debug into the program to see when the queries are issued.
If you want to eager load the children in LINQ to SQL, use the LoadOptions with the LoadWith operation.
protected void Button1_Click(object sender, EventArgs e)
{
MyDataContext context = new MyDataContext();
var lo = new DataLoadOptions();
lo.LoadWith<M>(m => m.D1s);
context.LoadOptions = lo;
M m = context.Ms.Single(n => n.id == id); // id is somehow provided
Grid1.DataSource = m.D1s;
Grid1.DataBind();
}
In this case, if you don't need the m since it was already set in the page load, just load the appropriate D1s without reloading M in the button click handler:
protected void Button1_Click(object sender, EventArgs e)
{
using (MyDataContext context = new MyDataContext())
{
IQueryable<D> D = context.D1s.Where(d => d.Mid == id);
// id is somehow provided
Grid1.DataSource = D;
Grid1.DataBind();
}
}

How do i know id of ListView item on OnItemUpdated?

I have suppliers table with id int value for each supplier. I'm trying to edit columns of this table inside of ListView.
i'm trying to access e arg but it doesn't have any data on id of the row i'm trying to update?
You need to set the ListView.DataKeyNames to contain the property name of the uniqueId
<asp:ListView runat="server" ID="LvSample" DataKeyNames="SupplierId"/>
Then the dataKey will be available in the update events. It is worth nothing that you might want to use the ItemUpdating event instead of the ItemUpdated as this happens before Update occurs.
protected void Page_Load(object sender, EventArgs e)
{
LvSample.ItemUpdating += new EventHandler<ListViewUpdateEventArgs>(LvSample_ItemUpdating);
LvSample.ItemUpdated += new EventHandler<ListViewUpdatedEventArgs>(LvSample_ItemUpdated);
}
void LvSample_ItemUpdated(object sender, ListViewUpdatedEventArgs e)
{
var supplierId = e.NewValues["SupplierId"];
}
void LvSample_ItemUpdating(object sender, ListViewUpdateEventArgs e)
{
var supplierId = e.Keys["SupplierId"];
}
use the sender instead of the e
protected void ListView1_ItemUpdated(object sender, ListViewUpdatedEventArgs e)
{
if ((sender as ListView) != null)
{
ListView l = (ListView)sender;
l.SelectedIndex;
l.etc..............
DataKey key = l.SelectedDataKey;
object k = key.Values["foo"];
}
}

Resources