Reloading and Updating using Entity Framework and DBContext - c#

Ok so I have tried a few things and keep getting stuck. I had the update button working at one point and now it will not update. The delete button will work and delete records but I can not get the gridview to refresh after the record is deleted. I also want the gridview to reload after the update button is pressed and the record is updated. Here is what I have:
protected void btnDelete_Click(object sender, EventArgs e)
{
switch (btnDelete.Text)
{
case DeleteButton:
try
{
if (txtLocationName.Text != null && txtSubAccountName.Text != null)
{
Location locationCheck = _context.Locations.ToList()
.First(x => x.Name == txtLocationName.Text && x.SubAccount == txtSubAccountName.Text);
if (locationCheck != null)
{
Location n = new Location
{
Id = grdvwLocationList.SelectedIndex,
Name = txtLocationName.Text,
SubAccount = txtSubAccountName.Text
};
_context.Locations.Remove(n);
_context.SaveChanges();
}
}
}
catch (Exception)
{
lblLocationNameNotification.Text = "Please type in a location/sub-account or select a location/sub-account that doesn't have a asset to delete.";
txtLocationName.Text = "";
txtSubAccountName.Text = "";
}
break;
case CancelButton:
Reload();
break;
}
}
public void PopulateLocationGridView()
{
var locations = _context.Locations.Where(l => l.CompanyId == CompanyId)
.OrderBy(l => l.Name)
.ToList();
grdvwLocationList.DataSource = locations;
grdvwLocationList.DataBind();
if (locations.Count > 0)
{
grdvwLocationList.SelectedIndex = 0;
RowSelected();
}
else
{
txtLocationName.Text = "";
txtSubAccountName.Text = "";
}
}
The add button works just fine it just seems to be refreshing the grid view

I have the following exampe working in a winforms application
The trick is the dset.local
private void Form1_Load(object sender, EventArgs e)
{
var dset = Db.Tasks; // Db is my context.
DbSet<Task> qry = dset;
qry.Load();
bindingSource1.DataSource =dset.Local.ToBindingList();
}
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
Debug.Print(Db.Tasks.Count().ToString());
bindingSource1.EndEdit();
Db.SaveChanges();
}

After working on it last night I knew there was something that I was missing. I ended up going about it like this:
protected void btnDelete_Click(object sender, EventArgs e)
{
try
{
_context = new IMSDBContext();
switch (btnDelete.Text)
{
case DeleteButton:
if (txtLocationName.Text != null && txtSubAccountName.Text != null)
{
Location location = _context.Locations.ToList()
.First(x => x.Name == txtLocationName.Text && x.SubAccount == txtSubAccountName.Text);
_context.Locations.Remove(location);
_context.SaveChanges();
PopulateLocationGridView();
grdvwLocationList.SelectedIndex = 0;
RowSelected();
}
break;
case CancelButton:
Reload();
break;
}
}
catch (Exception ex)
{
lblLocationNameNotification.Text = ex.Message;
}
finally
{
if (_context != null)
{
_context.Dispose();
}
}
}
I had tried to use the PopulateLocationGridView() and RowSelect() methods by themselves and it was still having trouble. I ended up putting in the grdvwLocationList.SelectedIndex = 0; in to set the selected index on the first index in the list instead of the index of the record that I just deleted. That is where I was having trouble. I thought that the SelectRow() would reselect the index again but I had to reset it back to another index. If there are any questions or comments please feel free. I am still learning and would like all of the advise that I can get.

Related

How to override a session

I have a question can I overwrite a session that I allredy have set (I set the the user specific department)
Session:
int depId = user.HtDepartments.FirstOrDefault().DepartmentId;
Session["DepId"] = depId;
I want to override this id that I saved in the session with a new "id" that the user selectes out of the RadComboBox.
So when the user is coming back to this page not his "pre selected" department is selected , selected is the new department that he slected before
My code so far:
protected void Page_Load(object sender, EventArgs e)
{
if (!this.Page.IsPostBack)
{
this.parameterDepId = this.Request["depId"];
if (string.IsNullOrEmpty(parameterDepId))
{
parameterDepId = Session["depId"].ToString();
}
this.LoadDE(parameterDepId);
this.UserGrid.DataBind();
}
}
Loading the session
Here how I load my department
protected void LoadDE(string depId)
{
IEnumerable<HtDepartment> departments = null;
if (this.selectedBu != null)
{
departments = this.selectedBu.HtDepartments;
}
this.rcbDepartments.DataTextField = "Name";
this.rcbDepartments.DataValueField = "DepartmentId";
this.rcbDepartments.DataSource = departments;
this.rcbDepartments.DataBind();
this.rcbDepartments.Items.Insert(0, new RadComboBoxItem("-All-"));
if (depId != null)
{
int index = this.rcbDepartments.Items.IndexOf(this.rcbDepartments.Items.Where(i => i.Value == depId).SingleOrDefault());
if (index > -1)
{
this.rcbDepartments.Items[index].Selected = true;
this.selectedDepartment = departments.Where(i => i.DepartmentId == int.Parse(depId)).SingleOrDefault();
}
}
}
protected void rcbDepatments_SelectedIndexChanged(object sender, RadComboBoxSelectedIndexChangedEventArgs e)
{
if (this.rcbDepartments.Items.Count > 1 && this.rcbDepartments.SelectedIndex > 0)
{
this.selectedDepartment = HtDepartment.GetById(int.Parse(e.Value));
parameterDepId = this.selectedDepartment.ToString();
}
else
{
this.selectedDepartment = null;
}
this.dataSourceFilterChanged();
}
A resume of my question:
How and where should I override my session in the load method or in SelectedIndexChanged ?
It makes sense to check for the saved variable when loading a page, as the user won't be able to interact with the controls until this method has completed.
private void OnLoad(object sender, EventArgs e)
{
this.parameterDepId = this.Request["depId"];
}
But to override it with a new value you simply set a new value. Then the next time you loaded the page this newly set value would be returned in the OnLoad method.
private void MyControl_SelectedIndexChanged(object sender, EventArgs e)
{
Session["DepId"] = MyControl.SelectedValue;
}
I'm finding your question a bit unclear but hopefully this answers the main point of it and helps with your code logic.

Keep State of Gridview

I have a gridview and I'm trying to keep the state of. Currently I have it where the user can edit inline( from within the gridview). Regularly I got this working:
protected void GridViewTower_RowEditing(object sender, GridViewEditEventArgs e)
{
//Set the edit index.
GridViewTower.EditIndex = e.NewEditIndex;
//Bind/Re-LoadData data to the GridView control.
LoadData();
Populate();
}
protected void GridViewTower_CancelEditRow(object sender, GridViewCancelEditEventArgs e)
{
//Reset the edit index.
GridViewTower.EditIndex = -1;
//Bind/Re-LoadData data to the GridView control.
LoadData();
Populate();
}
Problem is, I have 3 other features such sorting, dropdown that filters gridview, and a button search which also filters the girdview. When inline editing within any 3 of those modes, I can't control the state in which the gridview is in. Inside my gridview tag, I have both EnableViewState and ViewStateMode set to true.
How can I keep the state of the gridview within these modes?
public void LoadData()
{
if (Session["GridView"] != null)
{
GridViewTower.DataSource = Session["GridView"];
GridViewTower.DataBind();
//Response.Redirect("TowerManagement.aspx"); //
//Session["GridView"] = null;
}
else
{
WISSModel.WISSEntities context = new WISSModel.WISSEntities();
var tower = (from t in context.Towers
where t.isDeleted == false
select new
{
t.TowerId,
t.TowerName,
RangeName = t.Range.RangeName
}).ToList();
GridViewTower.DataSource = tower;
GridViewTower.DataBind();
ViewState["Sort"] = 0;
}
}
protected void Gridview_Sort(object sender, GridViewSortEventArgs e)
{
WISSModel.WISSEntities context = new WISSModel.WISSEntities();
var towers = (from t in context.Towers
where t.isDeleted == false
select new
{
t.TowerId,
t.TowerName,
rangeName = t.Range.RangeName
}).ToList();
DataTable gridviewTable = towers.CopyToDataTable();
gridviewTable.DefaultView.Sort = e.SortExpression + " " + ConvertSortDirectionToSql(e.SortDirection);
GridViewTower.DataSource = gridviewTable;
GridViewTower.DataBind();
Session["GridView"] = GridViewTower.DataSource;
}
You don't need to store whole table in the Session or ViewState. Just store values of SortExpression, SortOrder etc. Here's an example how you can do it.
In my code I have added two private properties to store sortorder and sortexpression:
private string SortOrder
{
get
{
// Toggle order after sorting
string _order = "ASC";//Default
if( ViewState["SortOrder"] != null && ViewState["SortOrder"].ToString() =="DESC")
{
_order = "DESC";
ViewState["SortOrder"] = "ASC";
}
else
{
ViewState["SortOrder"] = "DESC";
}
return _order;
}
set
{
string _order = value.ToLower() == "descending"? "DESC" : "ASC";
ViewState["SortOrder"] = _order;
}
}
private string SortExpression
{
get
{
return ViewState["SortExpression"] != null ? ViewState["SortExpression"].ToString() : "";
}
set
{
ViewState["SortExpression"] = value;
}
}
I have changed your GridView_Sort method to store the sort expression and sort order in newly added properties and called LoadData() method:
protected void Gridview_Sort(object sender, GridViewSortEventArgs e)
{
SortExpression = e.SortExpression;
//Disabled sort direction to enable toggling
//SortOrder = e.SortDirection.ToString();
LoadData();
}
The LoadData() method will be called from many places, whenever we want to load data into GridView. So I have changed it to this:
public void LoadData()
{
WISSModel.WISSEntities context = new WISSModel.WISSEntities();
var towers = (from t in context.Towers
where t.isDeleted == false
select new
{
t.TowerId,
t.TowerName,
rangeName = t.Range.RangeName
}).ToList();
DataTable gridviewTable = new DataTable();
gridviewTable.Columns.Add("TowerId");
gridviewTable.Columns.Add("TowerName");
gridviewTable.Columns.Add("rangeName");
foreach (var t in towers)
{
gridviewTable.Rows.Add(new object[] { t.TowerId, t.TowerName, t.rangeName });
}
if (!String.IsNullOrEmpty(SortExpression))
{
gridviewTable.DefaultView.Sort = String.Format("{0} {1}", SortExpression, SortOrder);
gridviewTable = gridviewTable.DefaultView.ToTable();
}
GridViewTower.DataSource = gridviewTable;
GridViewTower.DataBind();
}
Initially I call the LoadData() method in Page_Load() :
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
LoadData();
}
}
You can download the test project here.

repositoryitemhyperlinkedit show/hide according to the row data

I am using an XtraGridView control in my winform. Now I added a RepositoryItemHyperLinkEdit to it. But I want to show/hide each link according to the row data.
How can I achieve this?
Thanks for any help..
I tried the next code but it did not work, the cell did not be empty.
("Show link" part is ok, but String.Empty does not work)
private void xgvGrid_CustomColumnDisplayText(object sender, DevExpress.XtraGrid.Views.Base.CustomColumnDisplayTextEventArgs e)
{
if (e.Column == gcControlField)
{
if (xgvGrid.GetFocusedRowCellValue("ControlField") != null)
{
if (xgvGrid.GetFocusedRowCellValue("ControlField").ToString() == "LINK")
e.DisplayText = "Show link";
else
e.DisplayText = string.Empty;
}
}
}
You can add your checking in the event GridView.CustomColumnDisplayText.
e.g. Each row is bind to a Person instance
private void gridView1_CustomColumnDisplayText(object sender, DevExpress.XtraGrid.Views.Base.CustomColumnDisplayTextEventArgs e)
{
// gcLink is your column using repositoryitemhyperlinkedit
if (e.Column == gcLink)
{
var person = gridView1.GetRow(e.RowHandle) as Person;
if (person != null)
{
// Logic to show/hide the link based on other field
if (person.FirstName == "John")
e.DisplayText = string.Empty;
else
e.DisplayText = person.Link;
}
}
}

Linq update query

I want to update an existing record. I also have debugged my code. The int id variable gets the value, but I don't know why my record doesn't updated.
SQLDBDataClassesDataContext dContext = new SQLDBDataClassesDataContext();
protected void Page_Load(object sender, EventArgs e)
{
//if (!IsPostBack)
{
if (!string.IsNullOrEmpty(Request.QueryString["fname"]))
{
FirstNameTextBox.Text = Request.QueryString["fname"];
}
if (!string.IsNullOrEmpty(Request.QueryString["lname"]))
{
LastNameTextBox.Text = Request.QueryString["lname"];
}
if (!string.IsNullOrEmpty(Request.QueryString["cellnum"]))
{
CellNumberTextBox.Text = Request.QueryString["cellnum"];
}
}
}
protected void UpdateButton_Click(object sender, EventArgs e)
{
int id = Convert.ToInt32(Request.QueryString["id"]);
var updatequery1 = dContext.PersonalDetailTables
.Where(pd => pd.ID == id).SingleOrDefault();
if (updatequery1 != null)
{
updatequery1.FirstName = FirstNameTextBox.Text;
updatequery1.LastName = LastNameTextBox.Text;
updatequery1.CellNumber = CellNumberTextBox.Text;
dContext.SubmitChanges();
}
}
if (updatequery1 != null)
is updatequery1 null? If it's now, it'll just skip right over. Setup a breakpoint and step through.
Alternatively, change .SingleOrDefautl to .Single instead. This way if nothing's found, u'll get an exception, and u'll know what's up.
Call dContext.InsertOnSubmit(fooentity) method before calling dContext.SubmitChanges();.
For example.
var ctx = DB.fooDB;
fooobj.fooName= bar.fooName;
fooobj.fooID= bar.fooID;
if (fooobj.fooID== 0)
ctx.Locations.InsertOnSubmit(bar);
ctx.SubmitChanges();
I`ve got my Solution..
the only problem was of if(!ispostback) issue.
context.InvProductStockMasters
.Update(ps => ps.LocationID.Equals(invStockAdjustmentHeader.LocationID)
&& ps.ProductID.Equals(invStockAdjustmentDetail.ProductID),
ps => new InvProductStockMaster
{ Stock = ps.Stock - invStockAdjustmentDetail.OrderQty });

How to store previous selected item from `DropDownList`

I have a DropDownList, using which I have to store some values from the CheckBoxList in the database.
Before I select another index from the DropDownList, the values in the CheckBoxList has to be stored, prompting the user with an alert "Save before proceeding".
I am able to display the above mention alert message. But the problem is once i change the index it DropDownList, the previous selected index is lost.
Can someone kindly help me getting the previous selected value and select the same dynamically in DropDownList. Because the value is need to store in database.
The code for displaying alert message is:
protected void LOC_LIST2_SelectedIndexChanged(object sender, EventArgs e)
{
if (CheckBoxList2.Items.Count > 0)
{
Label7.Visible = true;
Label7.Text = "*Save List Before Proceeding";
}
With the use of Global variables.
Using the code below. PreviousIndex will hold the previous, and CurrentIndex will hold current.
int PreviousIndex = -1;
int CurrentIndex = -1;
protected void LOC_LIST2_SelectedIndexChanged(object sender, EventArgs e)
{
PreviousIndex = CurrentIndex;
CurrentIndex = myDropdownList.Position; // Or whatever the get position is.
if (CheckBoxList2.Items.Count > 0)
{
Label7.Visible = true;
Label7.Text = "*Save List Before Proceeding";
}
}
You can get the selected value first time the page load as
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack) // Because When postback occurs the selected valued changed.
{
ViewState["PreviousValue"] = ddl.SelectedValue;
}
}
and in your selected index change event update your previous value by the new value as
protected void ddl_SelectedIndexChanged(object sender, EventArgs e)
{
ViewState["NewValue"] = ddl.SelectedValue;
// Do your work with PreviousValue and then update it with NewValue so next you can acces your previousValue using ViewState["PreviousValue"]
ViewState["PreviousValue"] = ViewState["NewValue"];
}
or If you want to access selected value on different pages then save it in Session.
you can try with this code - bu using session caching
public string YourOldValue
{
get
{
if(Session["key"] != null)
return (string) Session["key"];
}
set
{
Session["key"] = value;
}
}
//Set value
YourOldValue = yourControl.SelectedValue;
protected void LOC_LIST2_SelectedIndexChanged(object sender, EventArgs e)
{
Session["SavedItem"] = LOC_LIST2.SelectedItem;
if (CheckBoxList2.Items.Count > 0)
{
Label7.Visible = true;
Label7.Text = "*Save List Before Proceeding";
}
}
after you access on value or text
SelectedItem item = Session["SavedItem"] as SelectedItem;
if(item !=null)
{
string something= item.Value;
string otherthing =item.Text;
}
So here's what finally worked for me. A combination of the answers above.
You have to track both previous and current selected index/value in the OnLoad handler of the page/control.
private int PreviousSelectedIndex
{
get { return (Page.ViewSate["prevIdx"] == null) ? -1 : (int)ViewSate["prevIdx"]; }
set { Page.ViewSate["prevIdx"] = value; }
}
private int CurrentSelectedIndex
{
get { return (Page.ViewSate["currIdx"] == null) ? -1 : (int)ViewSate["currIdx"]; }
set { Page.ViewSate["currIdx"] = value; }
}
protected override void OnLoad(EventArgs e)
{
if (!Page.IsPostBack)
{
PreviousDropDownValue = ddlYourDropDownList.SelectedValue;
CurrentDropDownValue = ddlYourDropDownList.SelectedValue;
}
else if (Page.IsPostBack && CurrentDropDownValue != ddlYourDropDownList.SelectedValue)
{
PreviousDropDownValue = CurrentDropDownValue;
CurrentDropDownValue = ddlYourDropDownList.SelectedValue;
}
}
After that you can compare the previous and current values with each other.

Categories

Resources