I have a form with some text input fields and 3 comboboxes, and a submit button, which is intended to save the data of the form into a table on a database. So when I click the submit button, after some debugging, I found out that at the moment of clicking it, there is no selected value for the comboboxes, thus bringing up errors and exceptions, and obviously not saving the data into the DB. BUT not only that, in addition, after the submit button is clicked, the comboboxes lose all of their values and the complete list that filled them dissappears, as if they were not initialized.
The sad part of all this (since I'm aware I could just review my code some more) is that when I do exactly the same, with the exact same code (same dll's and everything) on my ASP.NET Visual Studio server (on my local machine) everything works perfect, hence I'm writting into the same remote database, and after clicking the submit button the data saves into the DB, and the form stays normal with all comboboxes as they were before clicking.
Why does this happen only on the server? Why can it write and read from the database with no problem at all on local?
I think it could be related to the PostBack on my Page_Load method (I initialize the comboboxes at it, but only if it is NOT a PostBack)... So could this be an issue related to how does the IIS server work with PostBacks which might be different than the local ASP.NET server?
EDIT
I am adding the HTML code of the form
<form id="form1" runat="server">
<div class="popup" style="border: 1px solid #000; width: 600px;">
<table style="height: 148px; width: 584px">
<tr>
<td class="style1">
<table>
<tr>
<td>
<abbr title="El N° de Folio le será otorgado luego de haber guardado la necesidad."><asp:Label ID="Labe" runat="server" Text="Folio *" class="innerControl"></asp:Label></abbr>
</td>
<td colspan="2">
<abbr title="El N° de Folio le será otorgado luego de haber guardado la necesidad."><asp:TextBox ID="folTB" runat="server" Width="70px" class="innerControl" Enabled="false"></asp:TextBox></abbr>
</td>
<td>
<asp:Label ID="Label4" runat="server" Text="Fecha" class="innerControl"></asp:Label>
</td>
<td colspan="3">
<asp:TextBox ID="fecTB" runat="server" Width="100px" class="innerControl" Enabled="false"></asp:TextBox>
<asp:CalendarExtender ID="TextBox1_CalendarExtender" runat="server"
Enabled="True" TargetControlID="fecTB" DefaultView="Years" PopupButtonID="calBTN"></asp:CalendarExtender>
<asp:FilteredTextBoxExtender ID="FilteredTextBoxExtender1" runat="server"
FilterType="Numbers, Custom" ValidChars="-" TargetControlID="fecTB">
</asp:FilteredTextBoxExtender>
<asp:ScriptManager ID="ScriptManager1" runat="server"
EnableScriptGlobalization="True">
</asp:ScriptManager>
</td>
</tr>
<tr>
<td style="padding-right: 20px;">
<asp:Label ID="Label7" runat="server" Text="Beneficiarios" class="innerControl"></asp:Label>
</td>
<td style="padding-right: 20px;" colspan="2">
<asp:TextBox ID="benTB" runat="server" class="innerControl" Width="70px" Text="0" Enabled="false"></asp:TextBox>
<asp:FilteredTextBoxExtender ID="FilteredTextBoxExtender3" runat="server"
FilterType="Numbers" TargetControlID="benTB">
</asp:FilteredTextBoxExtender>
</td>
<td style="padding-right: 20px;">
<asp:Label ID="Label2" runat="server" Text="Intendencia" class="innerControl"></asp:Label>
</td>
<td colspan="3">
<asp:DropDownList ID="intDDL" runat="server" class="innerControl" Width="270px">
</asp:DropDownList>
</td>
</tr>
<tr>
<td>
<asp:Label ID="Label9" runat="server" Text="Mes / Año" class="innerControl"></asp:Label>
</td>
<td>
<asp:DropDownList ID="mesDDL" runat="server" class="innerControl">
</asp:DropDownList>
</td>
<td>
/
</td>
<td>
<asp:DropDownList ID="anoDDL" runat="server" class="innerControl">
</asp:DropDownList>
</td>
<td style="width: 50px;">
<asp:Label ID="Label1" runat="server" Text="_________" class="innerControl" ForeColor="White"></asp:Label>
</td>
<td>
<asp:Label ID="Label10" runat="server" Text="Meses" class="innerControl"></asp:Label>
</td>
<td>
<asp:TextBox ID="mesesTB" runat="server" Width="77px" class="innerControl"
Height="23px"></asp:TextBox>
<asp:FilteredTextBoxExtender ID="TBExtender" runat="server"
FilterType="Numbers" TargetControlID="mesesTB">
</asp:FilteredTextBoxExtender>
</td>
</tr>
</table>
</td>
</tr>
</table>
</div>
<br />
<asp:Label runat="server" Text="Características del Requerimiento:" class="popup"></asp:Label>
<br />
<div class="popup" style="border: 1px solid #000; width: 600px;">
<table style="height: 100px; width: 584px">
<tr>
<td class="style1">
<table>
<tr>
<td>
<asp:Label ID="Label3" runat="server" Text="Población:" class="innerControl"></asp:Label>
</td>
<td colspan="2">
<asp:TextBox ID="pobTB" runat="server" Width="70px" class="innerControl"></asp:TextBox>
</td>
<td>
<asp:Label ID="Label5" runat="server" Text="Fundamentación:" class="innerControl"></asp:Label>
</td>
<td rowspan="3">
<asp:TextBox ID="fundTB" runat="server" Width="221px" class="innerControl"
TextMode="MultiLine" Rows="7" Columns="35"></asp:TextBox>
</td>
</tr>
<tr>
<td style="padding-right: 20px;">
<asp:Label ID="Label6" runat="server" Text="Tasa Desempleo:" class="innerControl"></asp:Label>
</td>
<td style="padding-right: 20px;">
<asp:TextBox ID="empTB" runat="server" class="innerControl" Width="70px" ></asp:TextBox>
<asp:FilteredTextBoxExtender ID="FilteredTextBoxExtender2" runat="server"
FilterType="Numbers, Custom" ValidChars=".," TargetControlID="empTB">
</asp:FilteredTextBoxExtender>
</td>
<td>
%
</td>
</tr>
<tr>
<td style="padding-right: 20px;">
<asp:Label ID="Label8" runat="server" Text="Tasa Pobreza:" class="innerControl"></asp:Label>
</td>
<td style="padding-right: 20px;">
<asp:TextBox ID="pobrTB" runat="server" class="innerControl" Width="70px" ></asp:TextBox>
<asp:FilteredTextBoxExtender ID="FilteredTextBoxExtender4" runat="server"
FilterType="Numbers, Custom" ValidChars=".," TargetControlID="pobrTB">
</asp:FilteredTextBoxExtender>
</td>
<td>
%
</td>
</tr>
</table>
</td>
</tr>
</table>
</div>
<div class="popup" style="width: 601px;">
<table>
<tr>
<td align="center" colspan="6" class="style2">
<asp:Button ID="guardarNecesBTN" Text="Guardar" style="width: 110px;"
runat="server" onclick="guardarNecesBTN_Click" Visible="true"/>
<asp:Button ID="cerrarModBTN" Text="Cerrar" style="width: 110px;"
runat="server" onclick="closePopUp" Visible="false"/>
</td>
</tr>
<tr>
<td class="style2">
<asp:Label ID="Test" Text="" runat="server"></asp:Label>
</td>
</tr>
</table>
</div>
</form>
And this is the .cs codebehind
public partial class nueva_necesidad : System.Web.UI.Page
{
int fol = 0;
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
loadMeses();
loadAnos();
loadIntendencias();
String fec = DateTime.Today.Day.ToString();
fec = fec + "-" + DateTime.Today.Month.ToString();
fec = fec + "-" + DateTime.Today.Year.ToString();
fecTB.Text = (fec);
}
}
protected void loadIntendencias()
//Loads the intDDL with values taken from a DB table
{
intDDL.Items.Clear();
ListItem newItem = null;
List<entIntendencia> intList = new List<entIntendencia>();
intList = boNeces.loadIntendencias(Convert.ToInt32(Session["reg_usu"].ToString()), Convert.ToInt32(Session["niv_usu"].ToString()));
foreach (entIntendencia i in intList)
{
newItem = new ListItem();
newItem.Text = i.nombre;
newItem.Value = i.id_int.ToString();
intDDL.Items.Add(newItem);
}
}
protected void loadMeses()
//Loads the mesDDL, pre-selecting the (current month + 2) from the DDL
{
DateTime d = DateTime.Today;
int mesNum = d.Month;
ListItem newItem = null;
List<String> meses = new List<String>();
meses.Add("Enero");
meses.Add("Febrero");
meses.Add("Marzo");
meses.Add("Abril");
meses.Add("Mayo");
meses.Add("Junio");
meses.Add("Julio");
meses.Add("Agosto");
meses.Add("Septiembre");
meses.Add("Octubre");
meses.Add("Noviembre");
meses.Add("Diciembre");
for (int i = 0; i <= 11; i++)
{
newItem = new ListItem();
newItem.Text = meses[i];
newItem.Value = (i + 1).ToString();
mesDDL.Items.Add(newItem);
}
if (d.Month != 11 && d.Month != 12)
mesDDL.SelectedIndex = mesNum + 1;
else
{
if (d.Month == 11)
mesDDL.SelectedIndex = 0;
else
mesDDL.SelectedIndex = 1;
}
}
protected void loadAnos()
//Loads the anoDDL with a list of two: the current year and the next one.
{
anoDDL.Items.Clear();
DateTime d = DateTime.Today;
int ano = d.Year;
ListItem newItem = null;
List<int> list = new List<int>();
list.Add(ano);
list.Add(ano + 1);
foreach (int an in list)
{
newItem = new ListItem();
newItem.Text = an.ToString();
newItem.Value = an.ToString();
anoDDL.Items.Add(newItem);
}
}
protected bool validaNecesidad(out int inten, out int meses, out int mes, out int ano, out int pob)
//Validates the completion of the form's input fields.
{
inten = 0;
meses = 0;
mes = 0;
ano = 0;
pob = 0;
Test.Text = intDDL.SelectedValue.ToString() + mesesTB.Text; //This line is intended to load the values of one of the comboboxes and one of the input textboxes onto a label called "Test" that's on the form itself, to check if they do have values or not, this is the first instruction that executes when the save button is clicked.
if (!Int32.TryParse(intDDL.SelectedValue.ToString(), out inten))
{
Test.Text = Test.Text + "Error en DDL intendencia";
return false;
}
if (inten <= 0)
{
Test.Text = Test.Text + "Error en DDL intendencia";
return false;
}
if (!Int32.TryParse(mesesTB.Text, out meses))
{
Test.Text = Test.Text + "Error en TB meses";
return false;
}
if (meses <= 0)
{
Test.Text = Test.Text + "Error en TB meses";
return false;
}
if (!Int32.TryParse(mesDDL.SelectedValue, out mes))
{
Test.Text = Test.Text + "Error en DLL mes";
return false;
}
if (mes <= 0)
{
Test.Text = Test.Text + "Error en DLL mes";
return false;
}
if (!Int32.TryParse(anoDDL.SelectedValue, out ano))
{
Test.Text = Test.Text + "Error en DLL ano";
return false;
}
if (ano <= 0)
{
Test.Text = Test.Text + "Error en DLL ano";
return false;
}
if (!Int32.TryParse(pobTB.Text, out pob))
{
Test.Text = Test.Text + "Error en TB pob";
return false;
}
if (pob <= 0)
{
Test.Text = Test.Text + "Error en TB pob";
return false;
}
if (string.IsNullOrWhiteSpace(empTB.Text))
{
Test.Text = Test.Text + "Error en TB emp";
return false;
}
if (string.IsNullOrWhiteSpace(pobrTB.Text))
{
Test.Text = Test.Text + "Error en TB pobr";
return false;
}
if (string.IsNullOrWhiteSpace(fundTB.Text))
{
Test.Text = Test.Text + "Error en TB fund";
return false;
}
return true;
}
protected void guardarNecesBTN_Click(object sender, EventArgs e)
//Saves a new record on the NECESIDADES table.
{
int res = 0;
int inten = 0;
int meses = 0;
int mes = 0;
int ano = 0;
int pob = 0;
if (validaNecesidad(out inten, out meses, out mes, out ano, out pob))
{
res = boNeces.saveNeces(inten, meses, mes, ano, pob, empTB.Text, pobrTB.Text, fundTB.Text, Session["log_usu"].ToString());
if (res != 0)
{
Test.Text = Test.Text + "Folio creado correctamente con el N° " + res + ".";
Test.ForeColor = System.Drawing.Color.Green;
guardarNecesBTN.Visible = false;
cerrarModBTN.Visible = true;
intDDL.SelectedIndex = 0;
loadMeses(); loadAnos();
empTB.Text = ""; pobTB.Text = ""; pobrTB.Text = ""; fundTB.Text = "";
}
else
{
Test.Text = "Ha ocurrido un problema, favor intentar más tarde.";
Test.ForeColor = System.Drawing.Color.Gray;
guardarNecesBTN.Visible = false;
cerrarModBTN.Visible = true;
intDDL.SelectedIndex = 0;
loadMeses(); loadAnos();
empTB.Text = ""; pobTB.Text = ""; pobrTB.Text = ""; fundTB.Text = "";
}
}
else
{
Test.Text = Test.Text + "Faltan campos por completar.";
Test.ForeColor = System.Drawing.Color.Red;
}
}
protected void closePopUp(object sender, EventArgs e)
//Function used to call the JavaScript function that closes the modal popup.
{
ScriptManager.RegisterStartupScript(this, GetType(), "closeMod", "closeMod();", true);
}
}
FINAL EDIT:
I've already solved the issue. It was because of the enable view state property set to false on the application's configuration under IIS manager. Changed it to true and now it works same as local.
First of all, add clearing of mesDDL dropdown in loadMeses() function.
Secondly, where is your sql-query? I didn't find that.
Related
I have a problem. I created a couple of custom DataControlFields because I need to display data that doesn't come from a DataSource on a DataGrid.
I managed to get the controls unto the GridView but I can't manage to solve a couple of issues.
My controls do not persist their values between postbacks. I have the markup sitting inside an UpdatePanel which I set to Conditional. I then configured my triggers, excluding those of the GridView. I also tried setting the UpdateMode to Always. I get the same behavior here.
Here is my markup:
<asp:UpdatePanel UpdateMode="Conditional" ID="reportchooserUpdatePanel" runat="server">
<ContentTemplate>
<Triggers>
<asp:PostBackTrigger ControlID="ddlMonth" EventName="Load" />
<asp:PostBackTrigger ControlID="ddlMonth" EventName="SelectedIndexChanged" />
<asp:PostBackTrigger ControlID="ddlYear" EventName="DataBinding" />
<asp:PostBackTrigger ControlID="ddlYear" EventName="SelectedIndexChanged
<asp:PostBackTrigger ControlID="GenerateReportsButton" EventName="Click" />
</Triggers>
<table class="ms-formtable">
<tr>
<td class="ms-formlabel">
<asp:Label ID="MonthYearLabel" runat="server" Text=""></asp:Label>
</td>
<td class="ms-formbody align-right">
<asp:DropDownList OnSelectedIndexChanged="ddlMonth_SelectedIndexChanged" AutoPostBack="true" runat="server" ID="ddlMonth" OnLoad="ddlMonth_Load">
<asp:ListItem Value="1">Januar</asp:ListItem>
<asp:ListItem Value="2">Februar</asp:ListItem>
<asp:ListItem Value="3">März</asp:ListItem>
<asp:ListItem Value="4">April</asp:ListItem>
<asp:ListItem Value="5">Mai</asp:ListItem>
<asp:ListItem Value="6">Juni</asp:ListItem>
<asp:ListItem Value="7">Juli</asp:ListItem>
<asp:ListItem Value="8">August</asp:ListItem>
<asp:ListItem Value="9">September</asp:ListItem>
<asp:ListItem Value="10">Oktober</asp:ListItem>
<asp:ListItem Value="11">November</asp:ListItem>
<asp:ListItem Value="12">Dezember</asp:ListItem>
</asp:DropDownList>
</td>
<td class="ms-formbody align-right">
<asp:DropDownList OnSelectedIndexChanged="ddlYear_SelectedIndexChanged" AutoPostBack="true" OnDataBinding="ddlYear_DataBinding" ID="ddlYear" runat="server"></asp:DropDownList>
</td>
</tr>
<tr>
<td style="width:100%;" class="ms-formbody" colspan="3">
<asp:GridView AutoGenerateColumns="false" ShowHeaderWhenEmpty="true" CssClass="grid-view" Width="100%" ID="gvProjects" runat="server">
</asp:GridView>
</td>
<td></td>
<td></td>
</tr>
<tr>
<td class="ms-formtoolbar align-right" colspan="3">
<asp:HyperLink Target="_blank" Font-Size="X-Small" ID="hlGembox" NavigateUrl="http://www.gemboxsoftware.com/spreadsheet/free-version" runat="server"></asp:HyperLink>
<asp:Button OnClientClick="AddNotification('Please wait...')" ID="GenerateReportsButton" runat="server" Text="" OnClick="GenerateReportsButton_Click" />
</td>
<td></td>
<td></td>
</tr>
</table>
</ContentTemplate>
</asp:UpdatePanel>
And here is the code of one of my custom DataControlFields. They are basically the same except for the controls they display:
class TemplateDropDownControl : DataControlField
{
SPList reportslist = ListItemHelper.GetReportsList();
protected void InitializeDataCell(DataControlFieldCell cell, DataControlRowState rowState)
{
string ID = Guid.NewGuid().ToString();
DropDownList list = new DropDownList();
list.ID = ID;
FillContentTypeDropDown(list);
cell.Controls.Add(list);
}
public override void InitializeCell(DataControlFieldCell cell, DataControlCellType cellType, DataControlRowState rowState, int rowIndex)
{
//Call the base method.
base.InitializeCell(cell, cellType, rowState, rowIndex);
this.InitializeDataCell(cell, rowState);
}
protected override DataControlField CreateField()
{
return new BoundField();
}
public string DataField
{
get
{
object value = base.ViewState["DataField"];
if (value != null)
{
return value.ToString();
}
else
{
return string.Empty;
}
}
set
{
base.ViewState["DataField"] = value;
this.OnFieldChanged();
}
}
public override void ExtractValuesFromCell(System.Collections.Specialized.IOrderedDictionary dictionary, DataControlFieldCell cell, DataControlRowState rowState, bool includeReadOnly)
{
DropDownList list = cell.Controls[0] as DropDownList;
ListItem selectedValue = list.SelectedItem;
if (dictionary.Contains(DataField))
dictionary[DataField] = selectedValue.Value;
else
dictionary.Add(DataField, selectedValue.Value);
}
private void FillContentTypeDropDown(DropDownList ddlContentTypes)
{
if (reportslist == null)
return;
SPContentTypeCollection cts = reportslist.ContentTypes;
ddlContentTypes.Items.Clear();
foreach (SPContentType ct in cts)
{
ddlContentTypes.Items.Add(new ListItem() { Text = ct.Name, Value = ct.DocumentTemplateUrl + ct.DocumentTemplate.Replace("~site", "") });
}
}
}
And lastly, here is the code where I add these to my page. I set the AutoGenerateColumns property of the GridView to false in markup:
private void BindDataGrid()
{
DataTable table = new DataTable();
table = new DataTable();
table.Columns.Add(ResourceHelper.LoadResource(ResourceName.ProjectnumberTableString));
table.Columns.Add(ResourceHelper.LoadResource(ResourceName.TemplateString));
table.Columns.Add(ResourceHelper.LoadResource(ResourceName.FileFormatString));
gvProjects.Columns.Clear();
gvProjects.DataSource = null;
//Fill DataTable here...
BoundField projectnumberField = new BoundField();
projectnumberField.HeaderText = ResourceHelper.LoadResource(ResourceName.ProjectnumberTableString);
projectnumberField.DataField = ResourceHelper.LoadResource(ResourceName.ProjectnumberTableString);
FileFormatCheckboxControl checkBoxControl = new FileFormatCheckboxControl();
checkBoxControl.DataField = ResourceHelper.LoadResource(ResourceName.FileFormatString);
checkBoxControl.HeaderText = ResourceHelper.LoadResource(ResourceName.FileFormatString);
TemplateDropDownControl dropDownControl = new TemplateDropDownControl();
dropDownControl.DataField = ResourceHelper.LoadResource(ResourceName.TemplateString);
dropDownControl.HeaderText = ResourceHelper.LoadResource(ResourceName.TemplateString);
gvProjects.Columns.Add(projectnumberField);
gvProjects.Columns.Add(dropDownControl);
gvProjects.Columns.Add(checkBoxControl);
gvProjects.DataSource = table;
gvProjects.DataBind();
}
Anybody know what I'm doing wrong here?
EDIT: Maybe I should be mentioning that I display the form in a Sharepoint modal dialog.
Ok I solved it another way since I had not idea why my problem kept happening. I just use a asp:Table now and generate the whole thing from code-behind. I have one method for this which I call on every page postback. It's important to note to call this method only from Page_Load. It didn't work when I called it from Page_Init.
Here is my code:
private void BindDataGrid()
{
GenerateReportsButton.Enabled = true;
reportsTable.Rows.Clear();
TableHeaderRow headerrow = new TableHeaderRow();
TableHeaderCell pnumberheader = new TableHeaderCell();
TableHeaderCell templateheader = new TableHeaderCell();
TableHeaderCell fileFormatHeader = new TableHeaderCell();
pnumberheader.Text = ResourceHelper.LoadResource(ResourceName.ProjectnumberTableString);
templateheader.Text = ResourceHelper.LoadResource(ResourceName.TemplateString);
fileFormatHeader.Text = ResourceHelper.LoadResource(ResourceName.FileFormatString);
headerrow.Cells.Add(pnumberheader);
headerrow.Cells.Add(templateheader);
headerrow.Cells.Add(fileFormatHeader);
reportsTable.Rows.Add(headerrow);
if (ddlYear.SelectedItem == null || ddlMonth.SelectedItem == null)
{
int index = reportsTable.Rows.Add(new TableRow());
TableCell cell = new TableCell();
cell.ColumnSpan = 3;
cell.Text = ResourceHelper.LoadResource(ResourceName.NoListItemsForMonthYear);
reportsTable.Rows[index].Cells.Add(cell);
GenerateReportsButton.Enabled = false;
return;
}
//Get items here
if (items.Count == 0)
{
int index = reportsTable.Rows.Add(new TableRow());
TableCell cell = new TableCell();
cell.ColumnSpan = 3;
cell.Text = ResourceHelper.LoadResource(ResourceName.NoListItemsForMonthYear);
reportsTable.Rows[index].Cells.Add(cell);
GenerateReportsButton.Enabled = false;
return;
}
else
InsertRowIntoProjectTable("Intern", "Intern");
List<string> processedReports = new List<string>();
foreach(SPListItem item in items)
{
if (item[Variables.projectNumberField].ToString() != "Intern" && !processedReports.Contains(item[Variables.activityProject].ToString()))
{
InsertRowIntoProjectTable(item[Variables.activityProject].ToString(), item.ID.ToString());
processedReports.Add(item[Variables.activityProject].ToString());
}
}
}
Then you can just read the data like this:
foreach(TableRow row in reportsTable.Rows)
{
//Important since foreach also iterates over headerrow
if (row.Cells[1].Controls.Count > 0 && row.Cells[1].Controls[0] is DropDownList)
{
string value1= row.Cells[0].Text;
string value2= ((DropDownList)row.Cells[1].Controls[0]).SelectedValue;
//do stuff with the data
}
}
If anybody still finds the answer to my specific problem above, feel free to add it. I will mark it as accepted once verified that it works.
I have the following code-behind:
Random rndNum;
int inFirstOne, inSecondOne;
protected void Page_Load(object sender, EventArgs e)
{
rndNum = new Random();
int inFirst = rndNum.Next(1, 51);
int inSecond = rndNum.Next(50, 101);
lblFirst.Text = inFirst.ToString();
inFirstOne = inFirst;
lblSecond.Text = inSecond.ToString();
inSecondOne = inSecond;
}
public void ValidateForm(object sender, EventArgs e)
{
string strNum = tbValidation.Text;
int inCalc = inFirstOne + inSecondOne;
if (inCalc.ToString() == strNum)
{
lblIsValid.Text = "Correct";
}
else
{
lblIsValid.Text = "Please enter the correct result";
lblIsValid.ForeColor = Color.DarkRed;
}
}
ASP.net code:
...
<tr>
<td><h2>What is <asp:Label ID="lblFirst" Text="" CssClass="numGen" ClientIDMode="Static" runat="server" /> + <asp:Label ID="lblSecond" Text="" CssClass="numGen" ClientIDMode="Static" runat="server" />?</h2></td>
<td><asp:TextBox ID="tbValidation" ClientIDMode="Static" CssClass="tbTech" runat="server"></asp:TextBox> <asp:Label ID="lblIsValid" runat="server" /></td>
</tr>
<tr>
<td colspan="2" class="setRight">
<asp:Button ID="SubmitForm" ClientIDMode="Static" runat="server" Text="Submit" OnClick="ValidateForm" CssClass="btn" UseSubmitBehavior="false" />
</td>
</tr>
...
I am always seeing Please enter the correct result message.
How can I modify to ensure when the result is entered it works to validate the calculation from code-behind.
It's not clear how you're filling tbValidation but in any case unless you execute your page_load logic only if request it's not postback, variables inFirstOne and inSecondOnewill be overwritten on button click.
It seems you need to have this
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostback)
{
// do this only if it's the first request
rndNum = new Random();
int inFirst = rndNum.Next(1, 51);
int inSecond = rndNum.Next(50, 101);
lblFirst.Text = inFirst.ToString();
inFirstOne = inFirst;
lblSecond.Text = inSecond.ToString();
inSecondOne = inSecond
}
}
int inCalc = Convert.ToInt32(lblFirst.Text) + Convert.ToInt32(lblSecond.Text); worked.
I have a simple formview and simple modelbinding in webform:
<asp:FormView ID="frm" ItemType="SabaDoor2.Models.Content" SelectMethod="frm_GetItem" UpdateMethod="frm_UpdateItem" DataKeyNames="Id" runat="server">
<ItemTemplate>
<fieldset>
<legend>
<asp:Label ID="lblName" Text='<%# Item.Name %>' runat="server"></asp:Label>
</legend>
<p>
<label>descripion :</label>
<asp:Label ID="lblDescription" Text='<%# Item.Description %>' runat="server"></asp:Label>
</p>
<p>
<asp:Button ID="btnEdit" Text="edit" CommandName="Edit" runat="server" />
</p>
</fieldset>
</ItemTemplate>
<EditItemTemplate>
<fieldset>
<legend>
<asp:Label ID="lblName" Text='<%# Item.Name %>' runat="server"></asp:Label>
</legend>
<p>
<label>description :</label>
<asp:TextBox ID="txt" Text='<%# Item.Description %>' runat="server" ></asp:TextBox>
</p>
<p>
<asp:Button CommandName="Update" ValidationGroup="mainPropertyGroup" runat="server" ID="btnUpdate" Text="update" />
<asp:Button CommandName="Cancel" ValidationGroup="mainPropertyGroup" runat="server" ID="btnCancel" Text="cancel" />
</p>
</fieldset>
<br />
</EditItemTemplate>
</asp:FormView>
and in code:
Models.Model1Container _db = new Models.Model1Container();
protected void Page_Load(object sender, EventArgs e)
{
bindEvents();
lblResult.ForeColor = System.Drawing.Color.Green;
lblResult.Text = "";
if (!IsPostBack)
{
}
else
{
}
}
private void bindEvents()
{
frm.ItemUpdated += frm_ItemUpdated;
}
void frm_ItemUpdated(object sender, FormViewUpdatedEventArgs e)
{
if (e.Exception == null)
{
lblResult.ForeColor = System.Drawing.Color.Green;
lblResult.Text = "done!";
}
else
{
lblResult.ForeColor = System.Drawing.Color.Red;
lblResult.Text = "error:" + e.Exception.Message;
e.KeepInEditMode = true;
}
}
public SabaDoor2.Models.Content frm_GetItem([System.Web.ModelBinding.QueryString("Id")]int? Id)
{
return _db.Contents.Find(Id);
}
// The id parameter name should match the DataKeyNames value set on the control
public void frm_UpdateItem(int Id)
{
SabaDoor2.Models.Content item = null;
item = _db.Contents.Find(Id);
if (item == null)
{
// The item wasn't found
ModelState.AddModelError("", String.Format("Item with id {0} was not found", Id));
return;
}
var result = TryUpdateModel(item);
if (ModelState.IsValid)
{
_db.SaveChanges();
}
}
public override void Dispose()
{
_db.Dispose();
base.Dispose();
}
tryUpdateModel return true but my model(description field) doesn't update
:(
I find out logical error:
i have to initialize BindItem.Name property instd of item.Name
Text='<%# BindItem.Description %>'
i have serched all over the web and didnt find anything like what i am doing or any solution to my problam.
i have an xsd file that connects to mdb and i want to show 10 resukts at a time and to have the ability to page throw all the results,for now the status is that i get 62 results per page and when i am trying to go to the next page i dont recive any results.
what is wrong in my code
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="MainPage.aspx.cs"
Inherits="FaceBookSearchN.MainPage" %>
<%# Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="asp" %>
<%--<%# Register Src="~/ResultsControl.ascx" TagPrefix="Results" TagName="ResultsControl" %>--%>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<style type="text/css">
.accordionHeader
{
border: 1px solid blue;
color: White;
background-color: #5078B3;
font-family: Arial,Sans-Serif;
font-size: 12px;
font-weight: bold;
padding: 5px;
margin-top: 5px;
cursor: pointer;
}
.accordionHeader a, .accordionHeaderSelected a
{
color: #ffffff;
background: none;
text-decoration: none;
}
.accordionHeader a:hover, .accordionHeaderSelected a:hover
{
background: none;
text-decoration: underline;
}
.accordionHeaderSelected
{
border: 1px solid #2f4f4f;
color: White;
background-color: #5078B3;
font-family: Arial, Sans-Serif;
font-size: 12px;
font-weight: bold;
padding: 5px;
cursor: pointer;
}
.accordionContent
{
background-color: White;
border: 1px solid,#2f4f4f;
border-top: none;
padding: 5px;
padding-top: 10px;
}
</style>
<title></title>
</head>
<body dir="rtl">
<form id="form1" runat="server">
<div>
<table width="520px">
<tr>
<td>
<table width="100%">
<tr>
<td>
<asp:Label runat="server" Text="תחום" ID="lblProffesion"></asp:Label>
</td>
</tr>
<tr>
<td>
<asp:DropDownList runat="server" ID="ddlProffesion" DataTextField="profession_name"
DataValueField="profession_id" OnSelectedIndexChanged="ddlProffesion_SelectedIndexChanged"
AutoPostBack="true">
</asp:DropDownList>
</td>
</tr>
</table>
</td>
<td>
<table width="100%">
<tr>
<td>
<asp:Label runat="server" Text="אזור" ID="lblArea"></asp:Label>
</td>
</tr>
<tr>
<td>
<asp:DropDownList runat="server" ID="ddlArea" DataValueField="id_area" DataTextField="name_area"
AutoPostBack="true">
</asp:DropDownList>
</td>
</tr>
</table>
</td>
</tr>
<tr>
<td>
<table width="100%">
<tr>
<td>
<asp:Label runat="server" Text="תפקיד" ID="lblSubProffesion"></asp:Label>
</td>
</tr>
<tr>
<td>
<asp:DropDownList runat="server" ID="ddlSubProffesion" DataValueField="tat_pofession_id"
DataTextField="tat_pofession_name" AutoPostBack="true">
</asp:DropDownList>
</td>
</tr>
</table>
</td>
<td>
<table width="100%">
<tr>
<td>
<asp:Label runat="server" Text="אזור כתיבה חופשי" ID="lblFreetext"></asp:Label>
</td>
</tr>
<tr>
<td>
<asp:TextBox runat="server" ID="txtFreetext"></asp:TextBox>
</td>
</tr>
</table>
</td>
</tr>
<tr>
<td>
</td>
<td>
<asp:Button runat="server" Text="חיפוש" ID="btnSearch" OnClick="btnSearch_Click" />
</td>
</tr>
</table>
<div style="width: 520px">
<table width="520px" id="tblHeader" runat="server" style="background-color: #5078B3;
height: 25px">
<tr>
<td>
<asp:Label runat="server" ID="lblJobNum" Text="מס' משרה"></asp:Label>
</td>
<td>
<asp:Label runat="server" ID="lblJobName" Text="שם משרה"></asp:Label>
</td>
<td>
<asp:Label runat="server" ID="lblJobArea" Text="אזור עבודה"></asp:Label>
</td>
</tr>
</table>
<asp:Accordion ID="Accordion1" runat="server" AutoSize="None" FramesPerSecond="40" SelectedIndex="0" TransitionDuration="100"
FadeTransitions="true" RequireOpenedPane="true" SuppressHeaderPostbacks="true"
ContentCssClass="accordionContent" HeaderCssClass="accordionHeader" HeaderSelectedCssClass="accordionHeaderSelected">
</asp:Accordion>
<asp:Label ID="lblCurrentPage" runat="server"></asp:Label>
<asp:Button ID="btnPrev" runat="server" Text=" << " />
<asp:Button ID="btnNext" runat="server" Text=" >> " />
</div>
</div>
<asp:ToolkitScriptManager ID="Toolkitscriptmanager1" runat="server">
</asp:ToolkitScriptManager>
</form>
</body>
</html>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Web.UI.HtmlControls;
namespace FaceBookSearchN
{
public partial class MainPage : System.Web.UI.Page
{
private DataConnectionTableAdapters.table_professionTableAdapter adapterProf;
private DataConnectionTableAdapters.table_profession_tatTableAdapter adapterSubProf;
private DataConnectionTableAdapters.table_areaTableAdapter adapterArea;
private DataConnectionTableAdapters.ordersTableAdapter adapterOrdersNoParams;
private DataConnectionTableAdapters.ordersWithParamsTableAdapter adapterOrdersWithParams;
private DataConnection.table_professionDataTable profDT;
private DataConnection.table_profession_tatDataTable SubProfDT;
private DataConnection.table_areaDataTable areaDT;
private DataConnection.ordersDataTable ordersNoParamsDT;
private DataConnection.ordersWithParamsDataTable ordersWithParamsDT;
PagedDataSource pds;
public int CurrentPage
{
get
{
object o = this.ViewState["CurrentPage"];
if (o == null)
return 0;
else
return (int)o;
}
set
{
this.ViewState["CurrentPage"] = value;
}
}
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
OnLoad();
}
}
protected void OnLoad()
{
tblHeader.Visible = false;
profDT = new DataConnection.table_professionDataTable();
adapterProf = new DataConnectionTableAdapters.table_professionTableAdapter();
areaDT = new DataConnection.table_areaDataTable();
adapterArea = new DataConnectionTableAdapters.table_areaTableAdapter();
adapterProf.Fill(profDT);
adapterArea.Fill(areaDT);
//adapter.Fill(SubProfDT);
ddlProffesion.DataSource = profDT;
ddlProffesion.DataBind();
ddlProffesion.Items.Insert(0,new ListItem("בחר מקצוע", "0"));
ddlArea.DataSource = areaDT;
ddlArea.DataBind();
ddlArea.Items.Insert(0, new ListItem("בחר אזור", "0"));
ddlSubProffesion.Items.Insert(0, new ListItem("בחר תת מקצוע", "0"));
}
protected void ddlProffesion_SelectedIndexChanged(object sender, EventArgs e)
{
SubProfDT = new DataConnection.table_profession_tatDataTable();
adapterSubProf = new DataConnectionTableAdapters.table_profession_tatTableAdapter();
adapterSubProf.GetDataByID(int.Parse(ddlProffesion.SelectedValue));
SubProfDT = adapterSubProf.GetDataByID(int.Parse(ddlProffesion.SelectedValue));
ddlSubProffesion.DataSource = SubProfDT;
ddlSubProffesion.DataBind();
//ddlSubProffesion.Items.Insert(0, new ListItem("בחר תת מקצוע", "0"));
}
protected void btnSearch_Click(object sender, EventArgs e)
{
tblHeader.Visible = true;
if (int.Parse(ddlProffesion.SelectedValue) == 0 && int.Parse(ddlArea.SelectedValue) == 0)
{
ordersNoParamsDT = new DataConnection.ordersDataTable();
adapterOrdersNoParams = new DataConnectionTableAdapters.ordersTableAdapter();
adapterOrdersNoParams.FillOrdersNoParams(ordersNoParamsDT);
DataTable dt = new DataTable();
dt = ordersNoParamsDT;
pds = new PagedDataSource();
pds.DataSource = dt.DefaultView;
pds.AllowPaging = true;
pds.PageSize = 10;
pds.CurrentPageIndex = CurrentPage;
lblCurrentPage.Text = "Page: " + (CurrentPage + 1).ToString() + " " + "of" + " " + pds.PageCount.ToString();
btnPrev.Enabled = !pds.IsFirstPage;
btnNext.Enabled = !pds.IsLastPage;
ViewState["totalpages"] = pds.PageCount;
for (int i = 0; i < pds.PageCount; i++)
{
FileUpload fu = new FileUpload();
Button btnSubmit = new Button();
btnSubmit.Text = "שלח קורות חיים";
AjaxControlToolkit.AccordionPane pn;
pn = new AjaxControlToolkit.AccordionPane();
pn.ID = "pane" + i;
Label lblTitle = new Label();
Label lblJobName = new Label();
Label lblDesc = new Label();
lblTitle.Text = dt.Rows[i]["order_id"].ToString();
lblJobName.Text = dt.Rows[i]["description"].ToString();
//lblDesc.Text = dt.Rows[i]["description"].ToString();
//Accordion1.DataSource = pds;
//Accordion1.DataBind();
pn.HeaderContainer.Controls.Add(lblTitle);
pn.HeaderContainer.Controls.Add(lblJobName);
HtmlTable tableDesc = new HtmlTable();
HtmlTableRow row;
HtmlTableCell cell;
cell = new HtmlTableCell();
row = new HtmlTableRow();
cell.InnerHtml = dt.Rows[i]["notes"].ToString();
row.Cells.Add(cell);
tableDesc.Rows.Add(row);
fu.Width = Unit.Percentage(100.00);
pn.ContentContainer.Controls.Add(lblDesc);
pn.ContentContainer.Controls.Add(tableDesc);
pn.ContentContainer.Controls.Add(fu);
pn.ContentContainer.Controls.Add(btnSubmit);
Accordion1.Panes.Add(pn);
}
//int i = 0;
//foreach (DataRow dr in ordersNoParamsDT)
//{
// FileUpload fu = new FileUpload();
// AjaxControlToolkit.AccordionPane pn;
// pn = new AjaxControlToolkit.AccordionPane();
// pn.ID = "pane" + i;
// Label lblTitle = new Label();
// Label lblDesc = new Label();
// lblTitle.Text = dr["order_id"].ToString();
// //lblTitle.Text = "מס' משרה" +"|" + "שם משרה" +"|"+ "אזור עבודה"+ "|";
// pn.HeaderContainer.Controls.Add(lblTitle);
// lblDesc.Text = dr["description"].ToString();
// //pn.ContentContainer.Controls.Add(lblDesc);
// HtmlTable tableDesc = new HtmlTable();
// HtmlTableRow row;
// HtmlTableCell cell;
// HtmlTableCell cell2;
// cell = new HtmlTableCell();
// cell2 = new HtmlTableCell();
// row = new HtmlTableRow();
// cell.InnerHtml = dr["notes"].ToString();
// fu.Width = Unit.Percentage(100.00);
// cell2.Controls.Add(fu);
// row.Cells.Add(cell);
// tableDesc.Rows.Add(row);
// pn.ContentContainer.Controls.Add(tableDesc);
// Accordion1.Panes.Add(pn);
// i++;
//}
//Accordion1.DataSource = new System.Data.DataTableReader(ordersNoParamsDT);
//Accordion1.DataBind();
//ucResults.Proffesion = int.Parse(ddlProffesion.SelectedValue);
//ucResults.SubProffesion = 0;
//ucResults.Area = int.Parse(ddlArea.SelectedValue);
}
else
{
// ucResults.Proffesion = int.Parse(ddlProffesion.SelectedValue);
// ucResults.SubProffesion = int.Parse(ddlSubProffesion.SelectedValue);
// ucResults.Area = int.Parse(ddlArea.SelectedValue);
}
}
private void btnPrev_Click(object sender, System.EventArgs e)
{
// Set viewstate variable to the previous page
CurrentPage -= 1;
// Reload control
//ItemsGet();
}
private void btnNext_Click(object sender, System.EventArgs e)
{
// Set viewstate variable to the next page
CurrentPage += 1;
// Reload control
//ItemsGet();
}
}
}
Your OnLoad() method only triggers during the first page load. The data needs to be rebound every time the page is changed. Try removing the if(!IsPostBack) from the Page_Load method and see if it works.
I want to bind the CourseFee[] array to repeater.
I want to bind Amount and CourseFeeType.Descr in my repeater.
How do I bind it?
Sample Class
public class Order
{
public CourceFeeType FeeType;
public int Amount;
public int CourseFee;
public void AddFeeTypeDetails(CourceFeeType Fees)
{
FeeType = new CourceFeeType();
FeeType.Code = Fees.Code;
FeeType.Desc = Fees.Desc;
}
// Nested class
public class CourceFeeType
{
public String Code;
public String Desc;
}
}
Sample Form Load Code
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
List<Order> List = new List<Order>();
Order OrderObj = new Order();
Order.CourceFeeType Fees = new Order.CourceFeeType();
Fees.Code = "1";
Fees.Desc = "w2s";
OrderObj.Amount = 1;
OrderObj.AddFeeTypeDetails(Fees);
List.Add(OrderObj);
OrderObj = new Order();
OrderObj.Amount = 2;
Fees = new Order.CourceFeeType();
Fees.Code = "2";
Fees.Desc = "w22s";
OrderObj.AddFeeTypeDetails(Fees);
List.Add(OrderObj);
rpt.DataSource = List;
rpt.DataBind();
}
}
Repeater Item Bound Data Event Code
protected void rpt_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
{
Label lbl = (Label)e.Item.FindControl("lblDescription");
lbl.Text = ((Order)e.Item.DataItem).FeeType.Desc;
Label lblAmount = (Label)e.Item.FindControl("lblAmount");
lblAmount.Text = ((Order)e.Item.DataItem).Amount.ToString();
}
}
Sample HTML
<asp:Repeater ID="rpt" runat="server" OnItemDataBound="rpt_ItemDataBound">
<HeaderTemplate>
<table>
<tr>
<td>
Amount
</td>
<td>
Description
</td>
</tr>
</HeaderTemplate>
<ItemTemplate>
<tr>
<td>
<asp:Label ID="lblAmount" runat="server"></asp:Label>
</td>
<td>
<asp:Label ID="lblDescription" runat="server"></asp:Label>
</td>
</tr>
</ItemTemplate>
<FooterTemplate>
</table>
</FooterTemplate>
</asp:Repeater>