I am trying to use a ListView to pull in data from a database. It "works" on the first try if the value exists, but it has a problem when searching for values that don't and then trying again with any other value(even if that other value does exist).
When debugging, I noticed the following:
If I search for a value that doesn't exist in thedatabase, then try to search for one that does, the debugger goes from the line "bValid = true" directly to the method to get the data for the Listview (lstAuthorizations_GetData()). Instead it should go to bindData. It seems like its not processing the bValid = true line. Why would it break here? I've tried changing the line to other variations but no matter what it is, it doesn't seem to process in the right order
Code:
else //default
{
if(string.IsNullOrEmpty(Search_ANumber) && string.IsNullOrEmpty(Search_MemberID))
{
bValid = false;
errorMsg = "Either A Number or M ID are required";
}
else
{
bValid = true;
lstAuthorizations.FindControl("cColumn").Visible = false; // if not in ActiveExceptions, hide column //may want to move this to Line 214
}
}
if (bValid)
{
bindData();
}
protected void bindData()
{
//removeTextBoxValues(); //remove values from Textboxes since you got a response from the DB
ShouldSearch = true;
panelSearchResults.Visible = true;
lstAuthorizations.DataBind();
}
ListView's getdata method:
public IQueryable<Project.Data.databaseView> lstAuthorizations_GetData()
{
try
{
IQueryable<databaseView> query = dbVBA.databaseView.AsQueryable();
if (!String.IsNullOrEmpty(Search_AuthNumber))
{
query = query.Where(m => m.A_Number == Search_ANumber);
}
return query.OrderBy(a=>a.A_Number);
}
aspx:
<asp:ListView ID="lstAuthorizations" runat="server"
ItemPlaceholderID="litPlaceHolder"
ItemType="Project.Data.databaseView" SelectMethod="lstAuthorizations_GetData">
It seems to run the method to get data from the database twice when it actually returns a result (it goes to the lstAuthorizations_GetData() method, then it goes to data bind, then it goes to the lstAuthorizations_GetData() method again). In cases where I try a second value, it goes to the lstAuthorizations_GetData() method, but never goes to bind data.
Anyone know why this is failing?
I had to move hiding/displaying the control AFTER the data was binded. It works now:
if (bValid)
{
bindData();
lstAuthorizations.FindControl("cColumn").Visible = true;
Related
I am not quite sure if I am asking the right question. I assume other people have had this issue.
I built my own Blazor Grid component. I am using an bound to a property.
I have a function to load my grid. I changed my bound property to a full getter,setter. In the setter, I call my function to load the grid. This works fast and easy in pretty much all instances. But, I have one grid that when binding it will take a few extra seconds to complete.
The problem: I can't seem to figure out how to get my waiting spinner component to show when loading my grid.
Example Blazor Markup:
#if (dataGrid == null)
{
<hr />
<BitcoSpinner></BitcoSpinner>
}
else
{
<BitcoGrid TheGrid="dataGrid"></BitcoGrid>
}
Here is my property and GridLoading:
private string selectedGroup1 = "";
public string selectedGroup
{
get => selectedGroup1;
set
{
selectedGroup1 = value;
LoadGrid();
}
}
private void LoadGrid()
{
dataGrid = null;
PT_Grid_Admin ptGrid = new PT_Grid_Admin(permitTraxLibrary, gridParams);
dataGrid = ptGrid.ADMIN_FeeList(feeList.Fee_Key, selectedGroup);
}
You should define LoadGrid method asynchronously. Therefore, at the beginning of the program, when the data grid value is set, your spinner will be displayed until the data grid value is not received. Then, after receiving the data grid value, the else part of the condition will be executed and its value will be displayed to the user.
It may not take much time to receive information from the DB in local mode, so the following code can be used to simulate the delay:
System.Threading.Thread.Sleep(5000);
In general, I think that if your code changes like this, you can see the spinner.
private string selectedGroup1 = "";
public string selectedGroup
{
get => selectedGroup1;
set
{
selectedGroup1 = value;
LoadGrid();
}
}
private async Task LoadGrid()
{
dataGrid = null;
System.Threading.Thread.Sleep(5000);
.
.
}
Of course, it is better to load the datagrid in OnInitializedAsync method. For more info you can refer to this link.
I have a form that I would like to reuse for both adding a new record and editing an existing record. I am able to successfully load the page with the relevant data when I select a record from a GridView and I am able to update the db record appropriately. However, my issue is trying to use the form for both executions. Here is my logic in code behind: (I assign a session variable when I click on the row in GridView and this does work successfully)
protected void Page_Load(object sender, EventArgs e)
{
resultOutput.Visible = false;//Output results as to whether or not a record was added successfully is automatically hidden at page load
//Checking to see if session variable has been created
if (Session["editID"] != null)
{
//Create objects to get recipe data
dbCRUD db = new dbCRUD();
Recipe editRecipe = new Recipe();
//Grabbing session ID and assigning to a variable in order to remove the session variable
var id = Convert.ToInt32(Session["editID"]);
Session.Remove("editID");
//Call method to retrieve db data
editRecipe = db.SelectRecord(id);
//Populate results to text boxes
recordID.Text = id.ToString();
addName.Text = editRecipe.Name;
addTypeDDL.SelectedValue = editRecipe.Meal;
addDifficultyDDL.SelectedValue = editRecipe.Difficulty;
addCookTime.Text = editRecipe.Cook_Time.ToString();
addDirections.Text = editRecipe.Directions;
//Change Button Text
submitRecord.Visible = false;
changeRecord.Visible = true;
//Change Title Text
addEditTitle.Text = "Edit Recipe";
}
}
protected void submitRecord_Click(object sender, EventArgs e)
{
//Variables for execution results
var modified = "";
int returned = 0;
//Creating the recipe Object to pull the values from the form and
//send the recipe object as a parameter to the method containing insert stored procedure
//depending on Add or Edit
Recipe recipe = new Recipe();
recipe.Name = addName.Text;
recipe.Meal = addTypeDDL.Text;
recipe.Difficulty = addDifficultyDDL.Text;
recipe.Cook_Time = int.Parse(addCookTime.Text);
recipe.Directions = addDirections.Text;
//Creating object to access insert method
dbCRUD newRecord = new dbCRUD();
//Checking to see if the page is loaded for edit or new addition
if (Session["editID"] != null)
{
//If recordID exists, recipe will be passed as to UpdateRecord method
recipe.Recipe_ID = int.Parse(recordID.Text);
returned = newRecord.UpdateRecord(recipe);
modified = "has been edited.";
Session.Remove("editID");
}
else
{
//If recordID does not exist, record will be passed to InsertRecord method (new recipe)
returned = newRecord.InsertRecord(recipe);
modified = "added";
}
//Method returns 0 if successful, 1 if sql error, 2 if other error
if (returned == 1)
{
resultOutput.Text = "There was an sql exception";
resultOutput.Visible = true;
}
else if (returned == 2)
{
resultOutput.Text = "There was a non sql exception";
resultOutput.Visible = true;
}
else
{
resultOutput.Text = "\"" + addName.Text + "\" recipe " + modified;
resultOutput.Visible = true;
}
}
I have issues on the if(Session["editID"] != null) line - I am always moved to the else logic and the if logic never runs.
Here is my click method in the GridView:
protected void Grid_Recipe_SelectedIndexChanged(object sender, EventArgs e)
{
int index = Convert.ToInt32(Grid_Recipe.SelectedDataKey.Value);
Session["editID"] = index;
Response.Redirect("addRecord.aspx");
}
My question is how can I control execution during the submitRecord_Click event so that I call the appropriate method. Thanks!
Have you considered using
if(Page.IsPostBack)
{
code here
}
To detect whether you are posting back to the page? Then you could check your value of the item. I see no reason the code shouldn't be in the Session variable - have you tried putting a breakpoint in there to see if the code actually gets in there?
Also does your addRecord.aspx just add the record? If so, just add the record in this class, but use the PostBack check to see. Could you just make sure you are saving in the right context aswell:
// Outside of Web Forms page class, use HttpContext.Current.
HttpContext context = HttpContext.Current;
context.Session["editID"] = index;
...
int Id = (string)(context.Session["editID"]);
I was able to figure out my issue - which actually turned into two issues. First, I had to put my Page Load logic in a if(!IsPostBack) statement because I could not edit the page. Reason being is I was loading the originally posted data to the form on page load, which executed before my logic. Adding the if(!IsPostBack) control statement fixed this issue. From there, I'm still using a session variable to control code behind logic, only I made sure keep my session variable only between the form and the gridview. Basically, when the gridview loads and it is not a post back, the session variable is cleared. This let's me set a new session variable when I click on a row and then the session variable is cleared once I return to the grid to see the results. Thanks for the help!
When the DataGridView in my application is populated, the following method is fired:
public void OrderSelectionChanged()
{
ConfirmOrCancelChangesDialog();
// Get values from selected order and populate controls
if (view.OrderTable.SelectedRows.Count != 0)
{
OrderViewObject ovm = (OrderViewObject)view.OrderTable.SelectedRows[0].DataBoundItem;
selectedOrder = orderModel.GetOrderById(ovm.OrderId);
// Populate view controls with data from selected order
view.OrderID = selectedOrder.Id.ToString();
---->> view.OrderDateCreated = selectedOrder.DateCreated; <<-----
view.OrderDeliveryDate = selectedOrder.DeliveryDate;
PopulateOrderAddressControls(selectedOrder.Address);
PopulateOrderItemTableControl();
PopulateOrderWeightAndSumControls();
view.OrderNote = selectedOrder.Note;
// Enable buttons
view.DeleteOrderButtonEnabled = true;
view.NewOrderItemButtonEnabled = true;
}
else
{
view.DeleteOrderButtonEnabled = false;
}
}
For some reason, the "isSaved" variable is being changed from true to false at the row I marked with arrows and I can't figure out why. This is not supposed to happen and was never an issue before, but suddenly appeared.
The variable "isSaved" is being checked in the following method:
public void ConfirmOrCancelChangesDialog()
{
if (!isSaved)
{
DialogResult dialog = MessageBox.Show(Properties.Resources.SaveChanges,
Properties.Resources.SaveChangesTitle, MessageBoxButtons.YesNo);
if (dialog == DialogResult.Yes)
{
SaveOrder();
}
else
{
UndoChanges();
}
}
}
This is causing the save or cancel dialog to appear everytime the application is started, which obviously is wrong. Since the selection changed method is fired three times and isSaved is changed during the first run, the dialog pops up during the second time around. Through debugging step by step I could figure out at what point isSaved is changing, but not how or why.
View is the form, OrderDateCreated is a getter/setter for a DateTimePicker, selectedOrder is just an order object and DateCreated a Date. Am I missing something here?
Cheers!
It seem related to your code setting values to view object.
If you didn't create properties by your own, that object may have set properties which detects any change and setting the isSaved properties to false.
Try this workaround:
bool wasSaved = isSaved; //reference properly to your isSaved variable, and store it in the wasSaved local var
view.OrderID = selectedOrder.Id.ToString();
view.OrderDateCreated = selectedOrder.DateCreated;
view.OrderDeliveryDate = selectedOrder.DeliveryDate;
isSaved = wasSaved; //revert to the previous state
I was trying to output a single List variable that retrieves data from database via a CodeBehind code to a text field in ASPX:
<asp:TextBox ID="TBCluster" runat="server" CssClass="textbox"></asp:TextBox>
C# is used and the code goes something like this:
public List<shuffleDataList> pullShuffledData(SqlDataReader rdr)
{
List<shuffleDataList> callList = new List<shuffleDataList>();
if (rdr != null)
{
if (rdr.HasRows)
{
while (rdr.Read())
{
callList.Add(new shuffleDataList()
{
cluster = rdr.IsDBNull(5) ? null : rdr.GetString(5),
});
}
}
else
{
Response.Write("<script>alert('the data is null')</script>");
return null;
}
}
return callList;
}
The retrieval of cluster field will occur after a user clicks on a particular button and so my passing the variable goes into like the following:
protected void shuffle_Click(object sender, EventArgs e)
{
getdata();
TBCluster.Text = new shuffleDataList().cluster;
}
However nothing is displayed on the textfield. On the same query, I can display the data on a datagrid view but not on a text field? Any ideas why is this occuring?
Thank you
You don't actually appear to be calling your function. Also, since a Text property is generally a string.. you won't be able to assign a list to it (with any meaningful result). Therefore, I will make a heap of assumptions about your code.. and give you this:
var list = pullShuffledData(someReaderHere);
if (list != null)
TBCluster.Text = string.Join(", ", list.Select(x => x.cluster));
I have finally solved my issue:
string cluster = string.Empty;
DataSet ds = new DataSet();
List<shuffleDataList> list = pullShuffledData(rdr);
foreach(shuffleDataList item in list)
{
cluster = item.cluster;
}
TBCluster.Text = cluster;
It was supposed to be displayed early on but this gridview seems to be clearing the value of pullShuffledData once assigned
//gridviewShuffle.DataSource = pullShuffledData(rdr);
//gridviewShuffle.DataBind();
after commenting out, the cluster value finally appeared on text box. thanks
I have a rather simple problem (I bealive). I have this method:
void appointments_SearchCompleted(object sender, AppointmentsSearchEventArgs e)
{
if (e.Results.Count() == 0)
{
results = "no events for the selected day";
//MessageBox.Show(results);
}
else
{
results = e.Results.Count() + " events found";
sourceItem = e.Results;
//MessageBox.Show(results);
}
}
And I can't "save" both results and sourceItem variables(which are class fields).
The Message box inside this method shows everything correct, howerver, on the outside results reverts to the default value.
The answer is simple: I didn't get how ansynch download works.
In my case I had to create a reference to my MainPage class, and bind items in appointments_SearchCompleted method.
Simple as that.