Cant Get Data To Return To My Grid View Using Linq in ASP.NET - asp.net

Not sure why but i cant get my data to return. It starts out saying there is not data records to display. But when i select the month and year of the information i am looking for the grid view disappears. Any suggestions
NutritionEntities context;
protected void Page_Load(object sender, EventArgs e)
{
context = new NutritionEntities();
if (!IsPostBack)
{
for (int i = DateTime.Now.Year; i > 1988; i--)
{
ddlYear.Items.Add(new ListItem(i.ToString(), i.ToString()));
}
int selectedMonth = int.Parse(ddlMonth.SelectedValue);
int selectedYear = int.Parse(ddlYear.SelectedValue);
GridView1.DataSource =
from exercise in context.Exercises
where exercise.exerciseDate.Value.Month == selectedMonth && exercise.exerciseDate.Value.Year == selectedYear
select new
{
exercise.exerciseDate,
exercise.duration,
exercise.caloriesBurned,
exercise.averageHR,
exercise.distanceInMiles,
exercise.notes
};
GridView1.DataBind();
}
}
protected void ddlMonth_SelectedIndexChanged(object sender, EventArgs e)
{
int selectedMonth = int.Parse(ddlMonth.SelectedValue);
int selectedYear = int.Parse(ddlYear.SelectedValue);
GridView1.DataSource =
from exercise in context.Exercises
where exercise.exerciseDate.Value.Month == selectedMonth && exercise.exerciseDate.Value.Year == selectedYear
select new
{
exercise.exerciseDate,
exercise.duration,
exercise.caloriesBurned,
exercise.averageHR,
exercise.distanceInMiles,
exercise.notes
};
GridView1.DataBind();
}
protected void ddlYear_SelectedIndexChanged(object sender, EventArgs e)
{
int selectedMonth = int.Parse(ddlMonth.SelectedValue);
int selectedYear = int.Parse(ddlYear.SelectedValue);
GridView1.DataSource =
from exercise in context.Exercises
where exercise.exerciseDate.Value.Month == selectedMonth && exercise.exerciseDate.Value.Year == selectedYear
select new
{
exercise.exerciseDate,
exercise.duration,
exercise.caloriesBurned,
exercise.averageHR,
exercise.distanceInMiles,
exercise.notes
};
GridView1.DataBind();
}

you have verify the binding of your control grid, i suggest add only object to the datasource of the grid on the pageLoad when the postback its false like this:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
GridView1.DataSource =
from exercise in context.Exercises
where exercise.exerciseDate.Value.Month == selectedMonth && exercise.exerciseDate.Value.Year == selectedYear
select new
{
exercise.exerciseDate,
exercise.duration,
exercise.caloriesBurned,
exercise.averageHR,
exercise.distanceInMiles,
exercise.notes
};
}
GridView1.DataBind();
}
the problem is when you add the objects to datasource , when any event refresh the web page like select the control is unbinding, i hope help you,, see you!!

Related

Radio button selected index not working

So I have a sipme ASP.NET Web Page that prints the info of one's gender stacked dynamically in a radio button list:
protected void Page_Load(object sender, EventArgs e)
{
String[] genders = new String[2];
genders[0] = "Male";
genders[1] = "Female";
RadioButtonList1.DataSource = genders;
RadioButtonList1.DataBind();
RadioButtonList1.Items.Add(new ListItem("Neutral", "Zero"));
}
protected void Button1_Click(object sender, EventArgs e)
{
lblName.Text = txtName.Text;
lblSurname.Text = txtSurname.Text;
lblEmail.Text = txtMail.Text;
Panel1.Visible = true;
if (RadioButtonList1.SelectedIndex==0) lblGender.Text = "Male";
else lblGender.Text = "Female";
}
However when I launch the site no matter what I select it always writes female it's like the RadioButtonList1.SelectedIndex==0 isn't working.
Any ideas?
Bind radiobuttonlist in page_Load with !IsPostBack condition or your radiobuttonlist will bind every time you post your page. So your radiobuttonlist is reset to index -1 when you click the button_click.
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
{
String[] genders = new String[2];
genders[0] = "Male";
genders[1] = "Female";
RadioButtonList1.DataSource = genders;
RadioButtonList1.DataBind();
RadioButtonList1.Items.Add(new ListItem("Neutral", "Zero"));
}
}

Invalid CurrentPageIndex value. It must be >= 0 and < the PageCount

i want to bind my data Gridview but it throw an error.
i allow paging when i click on new page e.g 1.2.3 then the above error throw
here is my code.
the one is page index change and the other one is my method of BindGrid.
the error come when i click one new page 2 or 3 etc
updated code
protected void DataGrid1_PageIndexChanged(Object sender, DataGridPageChangedEventArgs e)
{
DataGrid1.CurrentPageIndex = e.NewPageIndex;
DataGrid1.DataSource = Session["data"] as DataTable;
DataGrid1.DataBind();
}
private void BindGrid()
{
DataTable data = storedProcedureManager.sp_inactiveFiles(
providerID,
days, CaseTypeID, CollectorID, user.UserRegID);
lblMsg.Text = data.Rows.Count + " Record's Found.";
log.Info(lblMsg.Text);
Session["data"] = data;
DataGrid1.DataSource = data;
DataGrid1.DataBind();
log.Info("Report Displayed.");
}
Problem what is happening is when you fetch the data again in BindGrid() method you must be getting less number of pages.so you can do two things.
1)If you are filtering your data then reset the page index to 1.
protected void DataGrid1_PageIndexChanged(Object sender, DataGridPageChangedEventArgs e)
{
BindGrid();
}
private void BindGrid()
{
DataTable data = storedProcedureManager.sp_inactiveFiles(
providerID,
days,CaseTypeID,CollectorID,user.UserRegID);
lblMsg.Text = data.Rows.Count + " Record's Found.";
log.Info(lblMsg.Text);
DataGrid1.DataSource = data;
DataGrid1.CurrentPageIndex = 0;
DataGrid1.DataBind();
log.Info("Report Displayed.");
}
2)If you are not filtering your data then store the datagrid value in a session object and use this for pageing.
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
{
BindGrid();
}
}
protected void DataGrid1_PageIndexChanged(Object sender, DataGridPageChangedEventArgs e)
{
DataGrid1.CurrentPageIndex = e.NewPageIndex;
DataGrid1.DataSource = Session["value"] as DataTable;
DataGrid1.DataBind();
}
private void BindGrid()
{
DataTable data = storedProcedureManager.sp_inactiveFiles(
providerID,
days,CaseTypeID,CollectorID,user.UserRegID);
lblMsg.Text = data.Rows.Count + " Record's Found.";
log.Info(lblMsg.Text);
Session["value"]=data;
DataGrid1.DataSource = data;
DataGrid1.DataBind();
log.Info("Report Displayed.");
}
DataGrid1.DataSource = data;
DataGrid1.DataBind();
DataGrid1.CurrentPageIndex = 0;
Reset the CurrentPageIndex to 0 after the page has been bound.

Duplicate columns get created while clicking "Edit" in asp:GridView

I have asp:GridView where I am using AutoGenerateEditButton="True" property to edit the grid row. Now the issue is whenever I click Edit button, the columns are populating again. For example If there 4 columns and if I click Edit than same 4 columns will reappear.
.ASPX Code:
<asp:GridView ID="grdEmpDetail" runat="server" CellPadding="4" ForeColor="#333333" GridLines="None"
OnRowEditing="grdEmpDetail_RowEditing"
OnRowCancelingEdit="grdEmpDetail_RowCancelingEdit"
OnRowUpdated="grdEmpDetail_RowUpdated"
AutoGenerateEditButton="True">
</asp:GridView>
Code Behind: To Dynamically bind data on grid
protected void Page_Load(object sender, EventArgs e)
{
WorkSampleBusiness.BusinessObject objBL = new WorkSampleBusiness.BusinessObject();
this.grdEmpDetail.AutoGenerateColumns = false;
try
{
DataTable dt = new DataTable();
dt = objBL.OrderDetail();
foreach (var col in dt.Columns)
{
if (col.ToString() == "ID" || col.ToString() == "First Name" || col.ToString() == "Last Name" || col.ToString() == "Business Phone" || col.ToString() == "Job Title")
{
BoundField objBoundField = new BoundField();
objBoundField.DataField = col.ToString();
objBoundField.HeaderText = col.ToString();
this.grdEmpDetail.Columns.Add(objBoundField);
}
}
this.grdEmpDetail.DataSource = dt;
this.grdEmpDetail.DataBind();
}
catch
{
throw;
}
}
Handle Edit Mode:
protected void grdEmpDetail_RowEditing(object sender, GridViewEditEventArgs e)
{
this.grdEmpDetail.EditIndex = e.NewEditIndex;
this.grdEmpDetail.DataBind();
}
protected void grdEmpDetail_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
this.grdEmpDetail.EditIndex = -1;
this.grdEmpDetail.DataBind();
}
OUTPUT: This is fine
ISSUE : This is where I am getting issue.
What am I missing here?
You are not checking for IsPostBack in your databinding code. As a result, each time you post to the page that code is being executed again and again. So each time you will add more columns.
Modify your handler like so:
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack) {
// All of your existing code goes here
}
}
Edit
It's a little more complicated than that. You DO actually need to re-bind your DataGrid to the data source when you click edit, but you just don't want to add the columns again. This requires that you break up your code some so that the code for data-binding can be re-used without being tied to the column addition.
First, let's create a method specifically for adding columns that appear on an input DataTable:
private void AddColumnsToDataGrid(DataTable dt) {
foreach (var col in dt.Columns) {
if (col.ToString() == "ID"
|| col.ToString() == "First Name"
|| col.ToString() == "Last Name"
|| col.ToString() == "Business Phone"
|| col.ToString() == "Job Title")
{
BoundField objBoundField = new BoundField();
objBoundField.DataField = col.ToString();
objBoundField.HeaderText = col.ToString();
this.grdEmpDetail.Columns.Add(objBoundField);
}
}
}
Next Create a Method for Databinding a DataTable to your grid:
private void DataBindGrid(DataTable dt) {
this.grdEmpDetail.DataSource = dt;
this.grdEmpDetail.DataBind();
}
Now that you've extracted some of that code out, you can re-use these methods where appropriate, and only add columns one time:
Page Load Handler
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack) {
WorkSampleBusiness.BusinessObject objBL = new WorkSampleBusiness.BusinessObject();
this.grdEmpDetail.AutoGenerateColumns = false;
try {
DataTable dt = objBL.OrderDetail();
AddColumnsToDataGrid(dt);
DataBindGrid(dt);
} catch {
// Side Note: If you're just re-throwing the exception
// then the try/catch block is completely useless.
throw;
}
}
}
Editing Handlers
protected void grdEmpDetail_RowEditing(object sender, GridViewEditEventArgs e)
{
this.grdEmpDetail.EditIndex = e.NewEditIndex;
WorkSampleBusiness.BusinessObject objBL = new WorkSampleBusiness.BusinessObject();
DataBindGrid(objBL.OrderDetail());
}
protected void grdEmpDetail_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
this.grdEmpDetail.EditIndex = -1;
WorkSampleBusiness.BusinessObject objBL = new WorkSampleBusiness.BusinessObject();
DataBindGrid(objBL.OrderDetail());
}
Try:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
Fill_Grid();
}
}
protected Void Fill_Grid()
{
if (grdEmpDetail.Columns.Count > 0)
{
for (int n = 0; n < grdEmpDetail.Columns.Count; n++)
{
grdEmpDetail.Columns.RemoveAt(n);
}
grdEmpDetail.DataBind();
}
this.grdEmpDetail.AutoGenerateColumns = false;
WorkSampleBusiness.BusinessObject objBL = new WorkSampleBusiness.BusinessObject();
try
{
DataTable dt = new DataTable();
dt = objBL.OrderDetail();
foreach (var col in dt.Columns)
{
if (col.ToString() == "ID" || col.ToString() == "First Name" || col.ToString() == "Last Name" || col.ToString() == "Business Phone" || col.ToString() == "Job Title")
{
BoundField objBoundField = new BoundField();
objBoundField.DataField = col.ToString();
objBoundField.HeaderText = col.ToString();
this.grdEmpDetail.Columns.Add(objBoundField);
}
}
this.grdEmpDetail.DataSource = dt;
this.grdEmpDetail.DataBind();
}
catch (exception e1)
{
}
}
protected void grdEmpDetail_RowEditing(object sender, GridViewEditEventArgs e)
{
this.grdEmpDetail.EditIndex = e.NewEditIndex;
Fill_Grid();
}
protected void grdEmpDetail_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
this.grdEmpDetail.EditIndex = -1;
Fill_Grid();
}

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.

UserAccounts_RowEditing/Updating is not working properly

Alright, so I have a Gridview and added RowEditing and RowUpdating to it, but it won't really edit something.. This is my code for both:
protected void UserAccounts_RowEditing(object sender, GridViewEditEventArgs e)
{
UserAccounts.EditIndex = e.NewEditIndex;
BindUserAccounts();
}
protected void UserAccounts_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
int index = UserAccounts.EditIndex;
GridViewRow row = UserAccounts.Rows[e.RowIndex];
username = UserAccounts.Rows[e.RowIndex].Cells[1].Text;
email = ((TextBox)row.Cells[2].Controls[0]).Text;
MembershipUser user = Membership.GetUser(username);
if (user != null)
{
user.Email = email;
Membership.UpdateUser(user);
ActionStatus.Text = string.Format("User {0} details have been successfully updated!", username);
}
UserAccounts.EditIndex = -1;
BindUserAccounts();
}
What am I doing wrong in here?
EDIT: This is my BindUserAccounts:
private void BindUserAccounts()
{
int totalRecords;
UserAccounts.DataSource = Membership.FindUsersByName(this.UsernameToMatch + "%", this.PageIndex, this.PageSize, out totalRecords);
UserAccounts.DataBind();
bool visitingFirstPage = (this.PageIndex == 0);
lnkFirst.Enabled = !visitingFirstPage;
lnkPrev.Enabled = !visitingFirstPage;
int lastPageIndex = (totalRecords - 1) / this.PageSize;
bool visitingLastPage = (this.PageIndex >= lastPageIndex);
lnkNext.Enabled = !visitingLastPage;
lnkLast.Enabled = !visitingLastPage;
}
i think the should be like this
protected void update_click_foredu(object sender, GridViewUpdateEventArgs e)
{
Label edui = (Label)edugrid.Rows[e.RowIndex].FindControl("label");
TextBox unitxt = (TextBox)edugrid.Rows[e.RowIndex].FindControl("txtuni");
if (unitxt != null && costxt != null && startdatetxt != null && enddatetxt != null)
{
using (Entities1 context = new Entities1())
{
string eduID = edui.Text;
model obj = context.entitytabel.First(x => x.ID == eduID);
obj.Univ_Name = unitxt.Text;
context.SaveChanges();
lblMessage.Text = "Saved successfully.";
edugrid.EditIndex = -1;
bindgrid();
}
}
}
here im using EF like this you can find the control of the text box and save it in gridview
hope this helps you
Somehow it works now after editing the GridView and set "UserName", "IsApproved", "IsLockedOut" and "IsOnline" to ReadOnly="true"

Resources