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();
}
}
Related
I can successfully select the data I want to update to another page and populate my text boxes but if I set the selected values to my textbox and then try to update it wouldn't work and the same data is shown in database table.
However if I DO NOT set those values to my textboxes, then I can successfully update which is not what I am after.
I would like the user to see the data and record that s being updated
Here is my code:
protected void Page_Load(object sender, EventArgs e)
{
UserClassesDataContext db= new UserClassesDataContext();
var qr = from user in db.Users
where user.user_id == new Guid(Request.QueryString["user_id"])
select user;
foreach (var q in qr)
{
TextBox1.Text = q.user_name;
TextBox2.Text = q.password;
}
}
protected void Button1_Click(object sender, EventArgs e)
{
UserClassesDataContext db = new UserClassesDataContext();
var qr = from user in db.Users
where user.user_id == new Guid(Request.QueryString["user_id"])
select user;
foreach (var q in qr)
{
q.user_name = TextBox1.Text;
q.password = TextBox2.Text;
}
db.SubmitChanges();
Response.Redirect("Default.aspx");
}
What am I doing wrong?
Thanks
The problem is, when you submit the button, the code inside Page_Load event is executing again.That means it is reading the data from your table and setting the value to textboxes(thus overwriting what user updated via the form ) and you are updating your record with this values (original values). So basically you are updating the rows with same values.
You can use the Page.IsPostBack property to determine whether the event is occurred by a postback(button click) or initial page load.
This should fix it.
protected void Page_Load(object sender, EventArgs e)
{
if(!Page.IsPostBack)
{
// to do: read and set to textbox here.
}
}
I have my website running on dotnetnuke 7.4, i have a checklistbox which i bind on the page load, and after selecting items from it, user clicks on the submit button, the selected items should save in database, however when i click on the submit button, checklistbox gets blank, i tried to enable ViewState at :
Web.config level
Page Level
Control Level
But all in vain, it still unbinds checklistbox because of which everything disappears, i tried the same in plain .net and it works like a charm.
Is there any specific settings in dotnetnuke to support viewstate, or is there any other better option to achieve this.
Here's my code:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
Entities objEntities = new Entities();
List<Entities> obj = objEntities.GetList(2);
chkBox.DataSource = obj;
chkBox.DataTextField = "Name";
chkBox.DataValueField = "ID";
chkBox.DataBind();
}
}
protected void btnSubmit_Click(object sender, EventArgs e)
{
foreach (ListItem item in chkBox.Items)
Response.Write(item.Text + "<br />");
}
There's the issue. Remove that (!IsPostBack) check in your page_load event. Have your code to be like below. Else, only at first page load you are binding the datasource to control which gets lost in postback.
protected void Page_Load(object sender, EventArgs e)
{
Entities objEntities = new Entities();
List<Entities> obj = objEntities.GetList(2);
chkBox.DataSource = obj;
chkBox.DataTextField = "Name";
chkBox.DataValueField = "ID";
chkBox.DataBind();
}
OR, to be more efficient; refactor your code to a method like below and store the data object in Session variable like
private void GetDataSource()
{
List<Entities> obj = null;
if(Session["data"] != null)
{
obj = Session["data"] as List<Entities>;
}
else
{
Entities objEntities = new Entities();
obj = objEntities.GetList(2);
}
chkBox.DataSource = obj;
chkBox.DataTextField = "Name";
chkBox.DataValueField = "ID";
chkBox.DataBind();
Session["data"] = obj;
}
Call the method in your Page_Load event like
protected void Page_Load(object sender, EventArgs e)
{
GetDataSource();
}
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();
}
I have a GridView and on its SelectedIndexChanged the code is fired:
protected void grdEntry_SelectedIndexChanged(object sender, EventArgs e)
{
lblAssignId.Text = grdEntry.SelectedRow.Cells[1].Text == " "
? ""
: grdEntry.SelectedRow.Cells[1].Text;
Ob.BranchId = Globals.BranchID;
Ob.AssignId = lblAssignId.Text;
DataSet dsMain = GetAssignDetails(Ob);
if (dsMain.Tables[0].Rows.Count != 0)
{
// some other code
Task.Factory.StartNew(() => FillMemberShipAndBarCode(dsMain.Tables[0].Rows[0]["CustomerCode"].ToString(), Ob.BranchId));
}
}
and the code for filling membership id is
private void FillMemberShipAndBarCode(string customerCode, string branchId)
{
var sqlCommand = new SqlCommand
{
CommandText = "sp_customermaster",
CommandType = CommandType.StoredProcedure
};
sqlCommand.Parameters.AddWithValue("#CustomerCode", customerCode);
sqlCommand.Parameters.AddWithValue("#BranchId", branchId);
sqlCommand.Parameters.AddWithValue("#Flag", 18);
var data = PrjClass.GetData(sqlCommand);
txtMemberShip.Text = data.Tables[0].Rows[0]["MembershipId"].ToString();
txtBarCode.Text = data.Tables[0].Rows[0]["Barcode"].ToString();
}
It's working fine, but is is not updating any of the textboxes. Also, I checked in watch window, the values are returned as expected (M-1213 and 634-98-4 ) and the code does reaches the point txtMemberShip.Text = data.Tables[0].Rows[0]["MembershipId"].ToString();
but the txtMemberShip just remains empty??? Can anyone tell me why is not updating the textboxes?
UPDATE
As per comments, here is the page load
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindDropDown();
BindGrid();
SetDefaultsInTextBoxes();
}
}
And I don't have any code that waits on this task.
Don't do this:
Task.Factory.StartNew(() => FillMemberShipAndBarCode(dsMain.Tables[0].Rows[0]["CustomerCode"].ToString(), Ob.BranchId));
What are you trying to achieve by doing so?
What is probably happening is your method FillMemberShipAndBarCode is probably running after ASP.NET has already sent the page back to the browser. Thus, essentially, no visible effect on the rendered HTML.
ASP.NET isn't a good place to do multi-threaded stuff.
Try just replacing the above with this:
FillMemberShipAndBarCode(dsMain.Tables[0].Rows[0]["CustomerCode"].ToString(), Ob.BranchId);
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"];
}
}