I realy need help for this. I am using AjaxControlToolkit.TabContainer and using ASP.NET Framework 4.0. Gridview,textbox and button are placed in TabContainer on asp page. When I press button postback does happen but its not binding gridview to datatable and textbox contents are also not updated.
I debug the code and found when i press button postback does happen and content does fill up in gridview and textbox value also assigned with new value. but values doesnt display on the page. I dont know why its happening. please help.
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack)
{
if (ListBoxCustomer.Items.Count != 0)
{
int[] _selectedItems = ListBoxCustomer.GetSelectedIndices();
string _comma = "";
string _custID = "";
InitializeConnection();
if (_selectedItems.Length != 0)
{
foreach (int i in _selectedItems)
{
_custID = _custID + _comma + ListBoxCustomer.Items[i].Value;
_comma = ",";
}
if (custObj != null)
{
//DataTable _dt = new DataTable();
DataSet _ds = new DataSet();
GridViewCustomer.Visible = true;
GridViewCustomer.AutoGenerateColumns = true;
_ds = custObj.GetSelectedCustomers(1, _custID);
GridViewCustomer.DataSource = _ds.Tables[0];
GridViewCustomer.DataBind();
TextBoxTest.Text = GridViewCustomer.Rows.Count.ToString();
TextBoxTest.Text = "test";
}
}
}
}
}
thanks.
Perhaps the DataBind code is never being reached. Have you set some breakpoints to make sure the if-statements aren't blocking you? That is... Is ListBoxCustomer.Items.Count definitely not zero... Is custObj definitely not null?
Where do you assign a value to custObj?
Related
There's a gridview in my program whose row's data is to be loaded in textboxes if edit is clicked.
Here is the code where I'm filling the data in textboxes after edit is clicked
protected void GV_Parameters_RowEditing(object sender, GridViewEditEventArgs e)
{
GV_Parameters.EditIndex = e.NewEditIndex;
int index = e.NewEditIndex;
IsEditing = true;
Label lbl_frmdate = (Label)GV_Parameters.Rows[index].FindControl("lbl_frmdate") as Label;
Label lbl_todate = (Label)GV_Parameters.Rows[index].FindControl("lbl_todate") as Label;
EditFromDate = lbl_frmdate.Text.ToUpper();
lbl_frm_edit.Text = EditFromDate;
EditToDate = lbl_todate.Text.ToUpper();
lbl_to_edit.Text = EditToDate;
Label lbl = (Label)GV_Parameters.Rows[index].Cells[3].FindControl("lbl_Is_holiday");
string is_holiday = lbl.Text;
Label lbl_std_intime = (Label)GV_Parameters.Rows[index].FindControl("lbl_std_intime") as Label;
Label lbl_std_outtime = (Label)GV_Parameters.Rows[index].FindControl("lbl_std_outtime") as Label;
string[] arr_std_intime;
string[] arr_std_outtime;
if (is_holiday != "1")//working day
{
r_work_holiday.SelectedIndex = 0;
IsHoliday = false;
if (lbl_std_intime.Text != "")
{
arr_std_intime = lbl_std_intime.Text.Split(':');
txt_std_TimeInHours.Text = arr_std_intime[0].ToString();
txt_std_TimeInMins.Text = arr_std_intime[1].ToString();
}
if (lbl_std_outtime.Text != "")
{
arr_std_outtime = lbl_std_outtime.Text.Split(':');
txt_std_TimeOutHours.Text = arr_std_outtime[0].ToString();
txt_std_TimeOutMins.Text = arr_std_outtime[1].ToString();
}
}
else
{
IsHoliday = true;
//r_workingday.Checked = false;
//r_holiday.Checked = true;
r_work_holiday.SelectedIndex = 1;
Label lbl_remarks = (Label)GV_Parameters.Rows[index].FindControl("lbl_remarks") as Label;
txt_holiday_desc.Text = lbl_remarks.Text;
}
collapse_state = "expand";
}
There is a radiobutton list who shows the edited row is holiday or working day,
if user changes the selection in radioButtonList, PostBack occurs and this is the time when all of the texboxes turn blank.
protected void r_work_holiday_SelectedIndexChanged(object sender, EventArgs e)
{
if(r_work_holiday.SelectedIndex==0)
{
IsHoliday = false;
}
else
{
IsHoliday = true;
}
collapse_state = "expand";
}
There's no any method in page load who is clearing the textboxes.
protected void Page_Load(object sender, EventArgs e)
{
if (IsEditing)
{
collapse_state = "expand";
}
if (!Page.IsPostBack)
{
BindYears();
}
}
Please help
Update ::
lbl_frm_edit and lbl_to_edit are not getting reset after postback.
The variable EditFromDate and EditToDate are being set by Viewstate
It's been sometime I worked in ASP controls but if I remember correctly, the content in textboxes are generally cleared on every post back by ASP .NET. The state of the textboxes are not saved.
Here is an answer I found while researching this issue.
You could store the value of the textboxes in ViewState and assign them back on the PageLoad event. Something like
txt_std_TimeOutHours.Text = arr_std_outtime[0].ToString();
txt_std_TimeOutMins.Text = arr_std_outtime[1].ToString();
ViewState["TimeOutHours"] = arr_std_outtime[0].ToString();
ViewState["TimeOutMins"] = arr_std_outtime[1].ToString();
And on the PageLoad event you can do this to restore the values.
if(Page.IsPostBack)
{
txt_std_TimeOutHours.Text = ViewState["TimeOutHours"].ToString();
txt_std_TimeOutMins.Text = ViewState["TimeOutMins"].ToString();
}
Hope this helps!
I am using Gridview with AutoGenerateColumns="True", so gridview columns are generated dynamically. Now in case of edit, I am adding dropdownlist dynamically for one of the field in the gridview. Please see following code:
protected void grdViewConfig_RowEditing(object sender, GridViewEditEventArgs e)
{
grdViewConfig.EditIndex = e.NewEditIndex;
BindGridView();
clientBAL = new TMIWsBALClient();
var lstAppIds = clientBAL.GetDistinctApplicationIds();
GridViewRow grdRow = grdViewConfig.Rows[e.NewEditIndex];
for (int i = 0; i < grdRow.Cells.Count; i++)
{
if (grdRow.Cells[i].GetType().Equals(typeof(DataControlFieldCell)))
{
DataControlFieldCell dcField = (DataControlFieldCell )grdRow.Cells[i];
if (dcField.ContainingField.HeaderText.ToLower().Equals("applicationid"))
{
DropDownList drpDwnAppIds = new DropDownList();
drpDwnAppIds.ID = "drpDwnAppIds";
drpDwnAppIds.DataSource = lstAppIds;
drpDwnAppIds.DataBind();
var tb = dcField.GetAllControlsOfType<TextBox>(); ;// grdRow.Cells[i].GetAllControlsOfType<TextBox>();
TextBox firstTb = (TextBox)tb.First();
foreach (ListItem lstItem in drpDwnAppIds.Items)
{
if (firstTb.Text.Equals(lstItem.Text, StringComparison.CurrentCultureIgnoreCase))
{
lstItem.Selected = true;
}
}
dcField.Controls.Remove(firstTb);
dcField.Controls.Add(drpDwnAppIds);
}
}
}
}
Now in Gridview_RowUpdating event, I am trying to fetch the dropdownlist in similar way, but I am unable to get it. GetAllControlsOfType() is an extension method, which will return all the child controls under selected parent. In this case, parent is gridview cell and child control is dropdownlist. But it is returning null.
protected void grdViewConfig_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
strTableName = txtTable.Text.Trim();
string strAppId;
GridViewRow grdRow = grdViewConfig.Rows[grdViewConfig.EditIndex];
for (int i = 0; i < grdRow.Cells.Count; i++)
{
if (grdRow.Cells[i].GetType().Equals(typeof(DataControlFieldCell)))
{
DataControlFieldCell dcField = (DataControlFieldCell)grdRow.Cells[i];
if (dcField.ContainingField.HeaderText.ToLower().Equals("applicationid"))
{
var drpDwn = dcField.GetAllControlsOfType<DropDownList>();
DropDownList drpDwnAppIds = (DropDownList)drpDwn.First();
strAppId = drpDwnAppIds.SelectedValue;
}
}
}
}
What am I missing? Please help. Also let me know if more information is needed.
Thank you in advance.
Dynamically generated controls need to be recreated on every postback. In your case the DropDownList controls you created no longer exist when you hit the grdViewConfig_RowUpdating handler.
Generally in this sort of case you would set AutoGenerateColumns to false and manually define your columns which would allow you to define a TemplateField which contains an ItemTemplate for read only mode and an EditItemTemplate for edit mode which could then contain your DropDownList.
I have the following button click event:
private void button_GetTrucks_Click(object sender, EventArgs e)
{
if (textBox_CompanyCode.Text.Length != 3)
{
_errorProvider.SetError(button_GetTrucks, "Invalid company code.");
return;
}
textBox_CompanyCode.Enabled = false;
button_GetTrucks.Enabled = false;
_corporationId = GetCorporationId(textBox_CompanyCode.Text);
if(_corporationId == Guid.Empty)
{
_errorProvider.SetError(button_GetTrucks, "Could not find company.");
return;
}
dataGridView1.DataSource = null;
_soureItemCollection = null;
textBox_CorporationId.Text = _corporationId.ToString();
var query = GetTrucks(_corporationId);
_soureItemCollection = new ObservableCollection<Truck>(query);
dataGridView1.DataSource = _soureItemCollection;
MakeDataGridViewPerty();
button_GetTrucks.Enabled = true;
textBox_CompanyCode.Enabled = true;
}
public static List<Truck> GetTrucks(Guid corporationId)
{
return (from trk in Entity.Trucks
where trk.CorporationId == corporationId
orderby trk.TruckNumber
select trk).ToList();
}
When I get the data initially by clicking the button, it works fine. If the data has changed, due to another program changing the data and I click this button again to refresh the data, it stays the same and does not display the changed data.
If I restart the application, click the button, the new data is displayed correctly.
So, it takes me restarting the application to reload the data.
Why is the button click not reloading the data?
I have seen where you have to add in a databind to get it to rebind
dataGridView1.DataSource = _soureItemCollection;
dataGridView1.Databind();
Before this call: var query = GetTrucks(_corporationId); place this one first:
Entity.Refresh(RefreshMode.OverwriteCurrentValues,Entity.Trucks);
I have this code which adds a x number of views to a Multiview control. The Multiview control exist on the page with only one view. on page init I create x number of views with a GridView control added to each of these views when I come to loop through to find which one I want to show the Multiview control says it has only 1 view.
protected void variantRepeat_ItemCommand(object source, RepeaterCommandEventArgs e)
{
if (e.CommandSource.GetType() == typeof(LinkButton))
{
string theID = ((LinkButton)e.CommandSource).CommandArgument.ToString();
ViewCollection views = prodView.Views; //this has only 1 view the one that has been added on the source view of the .aspx page
foreach (View toDisplay in views)
{
if (toDisplay.ID == theID)
prodView.SetActiveView(toDisplay);
}
}
}
The code above loops to find the view and display it. Why do all the views disappear, I've stepped through and at init and after it has finished processing database queries it has x number of views > the 1 in source view.
Why does this control "lose" the views?
Init code:
protected void Page_Load(object sender, EventArgs e)
{
if (Request.QueryString == null || Request.QueryString.Count < 1)
Response.Redirect(Server.MapPath("~/Packages/"));
if (!Page.IsPostBack)
{
if (Request.QueryString["id"].ToString() == string.Empty)
Response.Redirect(Server.MapPath("~/Packages/"));
var id = Server.HtmlEncode(Request.QueryString["id"].ToString());
Guid packID = Guid.Parse(id);
using (var context = new GaleEntities())
{
var thePackage = context.PackageEnts.First(p => p.packageID == packID);
var theVariants = thePackage.Variants;
var mydatasource = new List<PackageEnt> { thePackage };
var myVariantDataSource = new List<Variant>();
foreach (Variant single in theVariants)
{
myVariantDataSource.Add(single);
}
packageForm.DataSource = mydatasource;
variantRepeat.DataSource = myVariantDataSource;
RenderProductGridviews(theVariants);
prodView.SetActiveView(prodView.Views[0]);
}
packageForm.DataBind();
variantRepeat.DataBind();
Page.DataBind();
}
}
protected void RenderProductGridviews(System.Data.Objects.DataClasses.EntityCollection<Variant> variantCol)
{
foreach (Variant packVar in variantCol)
{
View newView = new View();
GridView prodGrid = new GridView();
var myProdDataSource = new List<vw_VariantProduct>();
using (var context = new GaleEntities())
{
var singleProd1 = context.vw_VariantProduct.Where(vp => vp.variantID == packVar.variantID);
foreach (vw_VariantProduct extProd in singleProd1)
{
myProdDataSource.Add(extProd);
}
}
prodGrid.DataSource = myProdDataSource;
BoundField _column = new BoundField();
_column.DataField = "product_title";
_column.HeaderText = "Product";
prodGrid.Columns.Add(_column);
_column = new BoundField();
_column.DataField = "product_title";
_column.HeaderText = "Product";
prodGrid.Columns.Add(_column);
_column = new BoundField();
_column.DataField = "product_desc";
_column.HeaderText = "Description";
prodGrid.Columns.Add(_column);
_column = new BoundField();
_column.DataField = "product_time";
_column.HeaderText = "Time (mins)";
prodGrid.Columns.Add(_column);
_column = new BoundField();
_column.DataField = "quantity";
_column.HeaderText = "Quantity";
prodGrid.Columns.Add(_column);
prodGrid.DataBind();
newView.ID = packVar.variantID.ToString();
newView.Controls.Add(prodGrid);
prodView.Views.Add(newView);
}
}
Now, as usual almost all questions with the dynamic controls in ASP.Net words share the same common problem...
You need to create the dynamic controls on every post, you are only creating them the first time the page is loaded. Follow this simple rules:
Dynamic controls should be created in the PreInit event when you are not working with a master page, if you are, then create the controls in the Init event
Avoid setting properties that can be changed in each post in these events because when the view state is applied (in a post event) the properties will be overridden
Dynamic controls must be created every time the page is posted, avoid this if(!this.IsPostBack) this.CreatemyDynamicControls();
When you create the controls in the PreInit or Init events, their states will be automatically set in a post event, which means in the LoadComplete event your controls will contain their state back even when you create them again in each post and even when you did not explicitly set their state. Note this behavior is different when you are dealing with controls created at design time, in that case, the event where the state has been set is the Load event
Event subscription should occur before the PageLoadComplete or they will not be raised
I have posted several answers about dynamic controls:
https://stackoverflow.com/a/11127064/1268570
https://stackoverflow.com/a/11167765/1268570
Click events on Array of buttons
Button array disappears after click event
Dynamically create an ImageButton
This piece of code creates dynamic controls on-demand, and each control keeps its state on each post
public partial class DynamicControlsOnDemand : System.Web.UI.Page
{
public int NumberOfControls
{
get
{
if (this.ViewState["d"] == null)
{
return 0;
}
return int.Parse(this.ViewState["d"].ToString());
}
set
{
this.ViewState["d"] = value;
}
}
protected void Page_PreLoad(object sender, EventArgs e)
{
this.CreateDynamicControls();
}
protected void addControl_Click(object sender, EventArgs e)
{
this.NumberOfControls = this.NumberOfControls + 1;
this.myPanel.Controls.Add(this.CreateTextbox(this.NumberOfControls));
}
private void CreateDynamicControls()
{
for (int i = 0; i < this.NumberOfControls; i++)
{
var t = this.CreateTextbox(i + 1);
t.TextChanged += (x, y) => this.lblMessage.Text += "<br/>" + (x as TextBox).ID + " " + (x as TextBox).Text;
this.myPanel.Controls.Add(t);
}
}
private TextBox CreateTextbox(int index)
{
var t = new TextBox { ID = "myTextbox" + index.ToString(), Text = "de" };
return t;
}
}
ASPX
<asp:Panel runat="server" ID="myPanel">
</asp:Panel>
<asp:Button Text="Add Control" runat="server" ID="addControl" OnClick="addControl_Click" />
<asp:Label ID="lblMessage" runat="server" />
Output
You first code block where you are setting the active View is based on an ItemCommand event, so I'm assuming this fires during a PostBack?
Your code which adds the additional views within Page_Load is only running if not a post back. Try removing the conditional if(!Page.IsPostBack) statement. You need to add dynamic controls on every page lifecycle.
I have some radiobuttons on some tabs, when I click on one it generates an Excel-file.
<asp:RadioButton ID="rbAantallen1" runat="server" AutoPostBack="True"
GroupName="Soort" oncheckedchanged="rbRapport_CheckedChanged"
Text="Aantallen" />
The bug happens when I want to switch to the other tab. It keeps generating Excel-files. What can I do to stop running the checkedchanged event and SWITCH IN PEACE TO ANOTHER TAB?
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
MyDataSource.SelectCommand = #"
select melder_account,
aanvraag_titel,
fase_datum_opgelost_oplosser,
Melding_niveau_2,
rapporteren,
fase_datum_gestart,
fase_datum_opgelost,
doorlooptijd,
jurentkode
from uvw_HD_AANVRAAG_DOORLOOPTIJD_ALGEMEEN
where Melding_niveau_1 = 'Brandje'";
}
}
protected void MenuTabs_MenuItemClick(object sender, MenuEventArgs e)
{
int index = Int32.Parse(e.Item.Value);
multiTabs.ActiveViewIndex = index;
MyDataSource.SelectCommand = BepaalDataSource(index);
}
public string BepaalDataSource(int index)
{
string select = #"
select melder_account,
aanvraag_titel,
fase_datum_opgelost_oplosser,
Melding_niveau_2,
rapporteren,
fase_datum_gestart,
fase_datum_opgelost,
doorlooptijd,
jurentkode
from uvw_HD_AANVRAAG_DOORLOOPTIJD_ALGEMEEN
where Melding_niveau_1 = '";
if (index == 0)
{
cbPage.Checked = false;
return select += "Brandje'";
}
else
{
cbPage.Checked = true;
return select += "System - Netwerk'";
}
}
public DataView GetDataFromDataSource()
{
MyDataSource.SelectCommand = BepaalDataSource(Convert.ToInt16(cbPage.Checked));
return MyDataSource.Select(DataSourceSelectArguments.Empty) as DataView;
}
protected void rbRapport_CheckedChanged(object sender, EventArgs e)
{
DataTable dtOriginal = (DataTable)GetDataFromDataSource().ToTable(); //Return Table consisting data
DataTable dtTemp = new DataTable(); //Create Temporary Table
//Creating Header Row
dtTemp.Columns.Add("<b>Melder</b>");
dtTemp.Columns.Add("<b>Onderwerp</b>");
dtTemp.Columns.Add("<b>Oplosser</b>");
dtTemp.Columns.Add("<b>Niveau 2</b>");
dtTemp.Columns.Add("<b>Rapporteren</b>");
dtTemp.Columns.Add("<b>Gestart op</b>");
dtTemp.Columns.Add("<b>Opgelost op</b>");
dtTemp.Columns.Add("<b>Doorlooptijd</b>");
dtTemp.Columns.Add("<b>Jurentkode</b>");
DataRow drAddItem;
for (int i = 0; i < dtOriginal.Rows.Count; i++)
{
drAddItem = dtTemp.NewRow();
drAddItem[0] = dtOriginal.Rows[i][0].ToString();//Melder
drAddItem[1] = dtOriginal.Rows[i][1].ToString();//Onderwerp
drAddItem[2] = dtOriginal.Rows[i][2].ToString();//Oplosser
drAddItem[3] = dtOriginal.Rows[i][3].ToString();//Niveau 2
drAddItem[4] = dtOriginal.Rows[i][4].ToString();//Rapporteren
drAddItem[5] = dtOriginal.Rows[i][5].ToString();//Gestart op
drAddItem[6] = dtOriginal.Rows[i][6].ToString();//Opgelost op
drAddItem[7] = dtOriginal.Rows[i][7].ToString();//Doorlooptijd
drAddItem[8] = dtOriginal.Rows[i][8].ToString();//Jurentkode
dtTemp.Rows.Add(drAddItem);
}
DataGrid dg = new DataGrid(); //Temp Grid
dg.DataSource = dtTemp;
dg.DataBind();
ExportToExcel("Rapport.xls", dg);
dg = null;
dg.Dispose();
}
private void ExportToExcel(string strFileName, DataGrid dg)
{
Response.ClearContent();
Response.AddHeader("content-disposition", "attachment; filename=" + strFileName);
Response.ContentType = "application/excel";
StringWriter sw = new StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(sw);
dg.RenderControl(htw);
Response.Write(sw.ToString());
Response.End();
}
protected void cbRapport_CheckedChanged(object sender, EventArgs e)
{
}
A couple things come to mind.
In your rbRapport_CheckChanged() function you could check to make sure the radio button is visible.
You could also check your tab control to make sure you're on the right tab.
EDIT
Based on your comments, the hosting tab is invisible.
If that's the case, do something like this in your code
rbRapport_CheckChanged()
{
if(tab1.Visible == false)
return;
<rest of code here>
}
Where tab1 is the tab that rbRapport is on. This will check, if the tab isn't visible, you probably don't want to create an xls, so it will just short circuit and kick out of the event. If the tab is visible, it will process the event.
Edit
maybe you shouldn't be creating the xls when your radio button changes. Maybe you should have a button to click that says "Generate XLS" or something, and capture that click event. – taylonr Apr 28 at 11:42
Nothing wrong with the code provided. Please ensure that, you have not bind this rbRapport_CheckedChanged function with any other control's event like TabChangedEvent or CheckedChange event of other radio button which values will be changing based on tab change etc.
If not so, there may be problem with the parent controls of the RadioButton.