I am having this kind of structure in a Web Application where depending on the user's choices Table_1 or Table_2 is given visibility; they never can be both visible.
<table>
<tr><td>
<table id="Table_1" runat="server" visible="false">
<tr><td>...</td></tr>
<tr><td>
<asp:GridView>
<asp:Linkbutton>
<asp:FormView>
</td></tr>
</table>
<table id="Table_2" runat="server" visible="false">
<tr><td>...</td></tr>
<tr><td>
<asp:GridView>
</td></tr>
</table>
</td></tr>
</table>
The strange thing is that this works only if the hole code block for table 2 is on top. If I switch them back to the way described by the code, table_2 never will show up. I do not add anything more. Just by switching the two tables in the code, once the result is correct, while in the other case it isn't.
What can this be related to?
Martin
Code that controls visibility:
protected void GridView01_OnSelectedIndexChanged(object sender, EventArgs e)
{
FilterDDLResponsable.SelectedIndex = -1;
GridView3.Visible = true;
GridView3.EditIndex = -1;
Table_1.Visible = true;
Table_2.Visible = false;
GridView3.DataBind();
ButtonEditMode.Visible = false;
ButtonSendHWReminderSeries.Visible = false;
if (AdminUser.Text == "1")
{
AddButton.Visible = true;
}
LabelAuditID.Text = Convert.ToString(GridView01.SelectedValue);
if(ActivateTabletView.Checked == true)
{
GridView01.Columns[12].Visible = true;
GridView01.Columns[13].Visible = true;
GridView01.Columns[14].Visible = true;
}
else
{
GridView01.Columns[12].Visible = false;
GridView01.Columns[13].Visible = false;
GridView01.Columns[14].Visible = false;
}
FillGrid();
}
and the Grid's row LinkButton onClick method:
protected void OpenAudit(object sender, EventArgs e)
{
LinkButton btn = (LinkButton)(sender);
string AuditID = btn.CommandArgument;
Table_1.Visible = false;
Table_2.Visible = true;
LabelAuditID.Text = AuditID;
foreach (GridViewRow gvRow in GridView01.Rows)
{
if ((int)GridView01.DataKeys[gvRow.DataItemIndex].Value == Convert.ToUInt32(AuditID))
{
GridView01.SelectedIndex = gvRow.DataItemIndex;
break;
}
}
FillQuestionsGrid();
}
Related
I have a form where there is a ListBox, a textbox and four buttons called Save, Edit, Delete and Clear. I'm retrieving data from database and populating the ListBox. When I select one of the items in the ListBox, it is populated into the textbox. Now when I delete that item, there is nothing wrong, it works fine. But when I try to update that item, i.e. change the text in the textbox and then click the Edit button, there is problem. In the textbox, I can see the text is being changed, no problem with that, but when I debugged, I found in the backend, the textbox is still containing the old text and not the modified one.
What am I doing wrong?
Here's my UI code:
<asp:Content ID="Content3" ContentPlaceHolderID="MainContent" runat="server">
<h1>Employee Category</h1>
<table>
<td>
<asp:ListBox ID="listEmployeeCategory" runat="server" Height="164px" Width="210px" AutoPostBack="true" />
</td>
<td>
<table>
<tr>
<td>
<asp:Label ID="lblMessage" runat="server" Text="" Visible="false" />
</td>
</tr>
<tr>
<td>
<asp:Label ID="lblEmpCategoryName" runat="server" Text="Name: " Font-Bold="true" />
</td>
<td>
<asp:TextBox ID="txtEmpCategoryName" runat="server" />
</td>
<td>
<asp:RequiredFieldValidator ID="rqdEmpCategoryName" ControlToValidate="txtEmpCategoryName" ErrorMessage="Employee Category Name can't be empty!" Style="color:Red" runat="server" />
</td>
</tr>
</table>
<asp:Button ID="btnSave" Text="Save" runat="server" OnClick="btnSave_Click" />
<asp:Button ID="btnEdit" Text="Edit" runat="server" OnClick="btnEdit_Click" />
<asp:Button ID="btnDelete" Text="Delete" runat="server" OnClick="btnDelete_Click" />
<asp:Button ID="btnCancel" Text="Cancel" runat="server" />
</td>
</table>
</asp:Content>
And here's my backend code, for the sake of everyone's understanding, I'm posting my entire backend code (except the BL, DAL and DAO codes):
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 Shelter.DAO.MasterEntry;
using Shelter.BLL.MasterEntry;
namespace Shelter.UI.MasterEntry
{
public partial class EmployeeCategoryUI : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
LoadDataIntoListBox();
}
else
{
if (listEmployeeCategory.SelectedIndex != -1)
{
LoadDataIntoTextBox(Convert.ToInt32(listEmployeeCategory.SelectedValue));
}
}
}
private void LoadDataIntoTextBox(int val)
{
EmployeeCategory objEmployeeCategory = new EmployeeCategory();
EmployeeCategoryBLL empCategoryBLL = new EmployeeCategoryBLL();
objEmployeeCategory.ID = Convert.ToInt32(val);
DataTable EmpCategoryDt = new DataTable();
EmpCategoryDt = empCategoryBLL.RetrieveById(objEmployeeCategory);
txtEmpCategoryName.Text = EmpCategoryDt.Rows[0]["EmpCategoryName"].ToString();
}
private void LoadDataIntoListBox()
{
EmployeeCategory objEmployeeCategory = new EmployeeCategory();
EmployeeCategoryBLL empCategoryBLL = new EmployeeCategoryBLL();
DataSet EmployeeCategoryDs = new DataSet();
EmployeeCategoryDs = empCategoryBLL.RetreiveFromTable();
DataTable EmployeeCategoryDt = EmployeeCategoryDs.Tables[0];
DataRow tempRow = null;
foreach (DataRow tempRow_Variable in EmployeeCategoryDt.Rows)
{
tempRow = tempRow_Variable;
string rowText = tempRow["EmpCategoryName"] + "(" + tempRow["ID"] + ")";
string rowValue = tempRow["ID"].ToString();
listEmployeeCategory.Items.Add(new ListItem(rowText, rowValue));
}
}
protected void btnSave_Click(object sender, EventArgs e)
{
EmployeeCategory objEmployeeCategory = new EmployeeCategory();
EmployeeCategoryBLL empCategoryBLL = new EmployeeCategoryBLL();
objEmployeeCategory.EmpCategoryName = txtEmpCategoryName.Text;
bool isSave = empCategoryBLL.SaveToTable(objEmployeeCategory);
if (isSave)
{
int id = empCategoryBLL.ReturnLastInsertedId();
lblMessage.Visible = true;
lblMessage.Style.Add("Color", "Green");
lblMessage.Text = "Data saved successfully!";
string rowText = txtEmpCategoryName.Text + "(" +id.ToString()+ ")" ;
string rowValue = id.ToString();
listEmployeeCategory.Items.Add(new ListItem(rowText, rowValue));
txtEmpCategoryName.Text = "";
}
else
{
lblMessage.Visible = true;
lblMessage.Style.Add("Color", "Red");
lblMessage.Text = "Data saving failed!";
}
}
protected void btnEdit_Click(object sender, EventArgs e)
{
if (IsPostBack)
{
EmployeeCategory objEmployeeCategory = new EmployeeCategory();
EmployeeCategoryBLL empCategoryBLL = new EmployeeCategoryBLL();
objEmployeeCategory.EmpCategoryName = txtEmpCategoryName.Text;
objEmployeeCategory.ID = Convert.ToInt32(listEmployeeCategory.SelectedValue);
bool isEdit = empCategoryBLL.EditInTable(objEmployeeCategory);
if (isEdit)
{
int id = objEmployeeCategory.ID;
lblMessage.Visible = true;
lblMessage.Style.Add("Color", "Green");
lblMessage.Text = "Data edited successfully!";
}
else
{
lblMessage.Visible = true;
lblMessage.Style.Add("Color", "Red");
lblMessage.Text = "Data editing failed!";
}
}
}
protected void btnDelete_Click(object sender, EventArgs e)
{
if (IsPostBack)
{
EmployeeCategory objEmployeeCategory = new EmployeeCategory();
EmployeeCategoryBLL empCategoryBLL = new EmployeeCategoryBLL();
objEmployeeCategory.ID = Convert.ToInt32(listEmployeeCategory.SelectedValue);
bool isDelete = empCategoryBLL.DeleteFromTable(objEmployeeCategory);
if (isDelete)
{
lblMessage.Visible = true;
lblMessage.Style.Add("Color", "Green");
lblMessage.Text = "Data deleted successfully!";
listEmployeeCategory.Items.Remove(new ListItem(listEmployeeCategory.SelectedItem.Text, listEmployeeCategory.SelectedValue));
txtEmpCategoryName.Text = "";
}
else
{
lblMessage.Visible = true;
lblMessage.Style.Add("Color", "Red");
lblMessage.Text = "Data deleting failed!";
}
}
}
}
}
The txtEmpCategoryName.Text is still containing the old value, so whenever I try to update, it only takes the old value and not the modified value in the textbox. It seems that the TextChanged event is not working. What is the fix to this problem?
You can use Entity frame in Visual studio;
right click on your solution - select new Add - then New Project - C# -Class Library give it a project name and Click Ok to add a new project to your existing project.
rename your class to a meaning name such as BusinessLogic and make it public.
right click on the newly added project and select add new item, on your popup windows select data on the right panel then select ADO.NET Entity Data Model rename your edmx to a meaningful name and click on add. default option and click on next, point to your SQL database by clicking on the new Connection.
select your store procedure for populating your listbox and updating the description and click on Finish.
CREATE PROCEDURE Proc_name AS BEGIN SET NOCOUNT ON;
SELECT ID,Description FROM Table_Name END
CREATE PROCEDURE [dbo].[UpdateEmpCategoryBLL]
#ID int, #Description varchar(50) AS BEGIN
SET NOCOUNT ON;
UPDATE Question1 SET Description = #Description WHERE ID = #ID
END
In your class Implement your methods for populating listbox and updating the description
public class Wrapper
{
public static List EmployeeCategory()
{
try
{
return new LOOKUPEntities().empCategoryBLL().ToList();
}
catch (Exception)
{
throw;
}
}
public static void UpdateEmpCategory(int id, string description)
{
try
{
using (LOOKUPEntities client = new LOOKUPEntities())
{
client.UpdateEmpCategoryBLL(id, description);
}
}
catch (Exception)
{
throw;
}
}
}
copy the connection string from you app.config to your web.config. Then add your class library to your references by right clicking on your references and select add reference, select solution and click on add. Add also System.Data,Entity and click ok.
now;
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
BindListBox();
}
}
protected void BindListBox()
{
try
{
ListItem lstBox;
listEmployeeCategory.Items.Clear();
var query = Wrapper.EmployeeCategory();
foreach (var items in query)
{
lstBox = new ListItem(items.Description, items.ID.ToString());
listEmployeeCategory.Items.Add(lstBox);
}
}
catch(Exception ex)
{
lblMessage.Visible = true;
lblMessage.Style.Add("Color", "Red");
lblMessage.Text = "Data loading failed "+ ex +" !";
}
}
protected void listEmployeeCategory_SelectedIndexChanged(object sender, EventArgs e)
{
lblMessage.Visible = false;
try
{
Session["ID"] = listEmployeeCategory.SelectedValue.ToString();
txtEmpCategoryName.Text = listEmployeeCategory.SelectedItem.ToString();
}
catch (Exception ex)
{
lblMessage.Visible = true;
lblMessage.Style.Add("Color", "Red");
lblMessage.Text = "Loading session data failed " + ex + " !";
}
}
protected void btnEdit_Click(object sender, EventArgs e)
{
try
{
int id = int.Parse(Session["ID"].ToString());
Wrapper.UpdateEmpCategory(id, txtEmpCategoryName.Text.Trim());
lblMessage.Visible = true;
lblMessage.Style.Add("Color", "Green");
lblMessage.Text = "Data edited successfully!";
BindListBox();
txtEmpCategoryName.Text = string.Empty;
}
catch
{
lblMessage.Visible = true;
lblMessage.Style.Add("Color", "Red");
lblMessage.Text = "Data editing failed!";
}
}
done!
I have the following repeater wrapped in an Update Panel
<asp:ScriptManager ID="ScriptManager1" runat="server" />
<asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Conditional">
<Triggers>
<asp:AsyncPostBackTrigger ControlID="DropDownList1" EventName="SelectedIndexChanged" />
</Triggers>
<ContentTemplate>
<asp:Repeater ID="skillTable" runat="server">
<ItemTemplate>
<table class="table table-hover">
<tr>
<td>
<asp:ImageButton runat="server" AutoPostBack="True" ID="skillButton" OnClick="skillButton_Click" CommandArgument="<%# Eval(DropDownList1.SelectedValue)%>" class="addText btn btn-success" ImageUrl="~/img/addbut.png" /></td>
<td><asp:Label runat="server" id="skillName" Text='<%# DataBinder.Eval(Container.DataItem, DropDownList1.SelectedValue) %>'></asp:Label></td>
</tr>
</table>
</ItemTemplate>
</asp:Repeater>
</ContentTemplate>
</asp:UpdatePanel>
It kicks out the information from my database perfectly, and it has a button right before the text in each row.
The problem that i have is that I need each button on each row to, when clicked, add the specific line of code in that row to a textbox.
foreach (RepeaterItem item in skillTable.Items)
{
string skill = item.DataItem.ToString();
string text = skillList.Text;
if (!string.IsNullOrEmpty(text))
{
if (!text.Contains(skill))
{
text += " | " + skill;
skillList.Text = text;
}
}
else
{
text = skill;
skillList.Text = text;
}
}
UpdatePanel2.Update();
I have also tried this way,
protected void skillTable_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
int d = 0;
if(DropDownList1.SelectedValue == "Business and Finance")
{
d = 1;
}
else if(DropDownList1.SelectedValue == "Computers and Technology")
{
d = 2;
}
else if (DropDownList1.SelectedValue == "Education")
{
d = 3;
}
else if (DropDownList1.SelectedValue == "Customer Service")
{
d = 4;
}
DataRowView drv = (DataRowView)e.Item.DataItem;
string skill = drv[d].ToString();
Session["Table"] = skill;
}
protected void skillButton_Click(object sender, System.Web.UI.ImageClickEventArgs e)
{
string skill = (string)(Session["Table"]);
string text = skillList.Text;
if (!string.IsNullOrEmpty(text))
{
if (!text.Contains(skill))
{
text += " | " + skill;
skillList.Text = text;
}
}
else
{
text = skill;
skillList.Text = text;
}
UpdatePanel2.Update();
}
but neither one of them seems to work correctly. Any advice? I havent really used repeaters before this, so If there is any other tool that would work better, I'm open for suggestions.
Thanks in advance!
So I figured it out. What I was missing was a way for my site to specifically narrow down what i needed. I added the code blow to my click method and got rid of the ItemDataBound method and it worked like a charm.
Button button = (sender as Button);
string commandArgument = button.CommandArgument;
RepeaterItem item = button.NamingContainer as RepeaterItem;
var workText = (Label)item.FindControl("workName1") as Label;
string work = workText.Text;
string text = workDetails1.Text;
if (text == " ")
text = "";
if (text == "")
{
if (!text.Contains(work))
{
text +="\u2022 " + work;
workDetails1.Text = text;
}
}
else if (!string.IsNullOrEmpty(work))
{
if (!text.Contains(work))
{
text += "\n\u2022 " + work;
workDetails1.Text = text;
}
else
{
workDetails1.Text = text;
}
}
UpdatePanel4.Update();
Hope this helps someone!
I`m trying to make an ASP.NET basic site that connects to a database. It's supposed to allow a user to register and log in.
I check the input with javascript and in the code behind in case it's disabled.
The problem is that whenever i click the register, login, or logout buttons for the first time they won't work; The page remains the same.
The second time, however, they work perfectly.
Debugger says it's called both times.
any ideas?
ASP:
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="Main.aspx.cs"
Inherits="Register_and_Login.Main" %>
<!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 id="Head1" runat="server">
<script type="text/javascript">
function isUserValid() {
var UserLength = document.getElementById("UserTB").value.length;
var ValidatorLabel = document.getElementById("ValidateUser");
if (UserLength < 6 || UserLength > 15) {
ValidatorLabel.style.display = 'inline';
return false;
}
else {
ValidatorLabel.style.display = 'none';
return true;
}
}
function isPassValid() {
var PassLength = document.getElementById("PasswordTB").value.length;
var ValidatorLabel = document.getElementById("ValidatePassword");
if (PassLength < 6 || PassLength > 15) {
ValidatorLabel.style.display = 'inline';
return false;
}
else {
ValidatorLabel.style.display = 'none';
return true;
}
}
function isConfirmValid() {
var Password = document.getElementById("PasswordTB").value;
var Me = document.getElementById("ConfirmTB").value;
var ValidatorLabel = document.getElementById("ValidateConfirm");
if (Password == Me) {
ValidatorLabel.style.display = 'none';
return true;
}
else {
ValidatorLabel.style.display = 'inline';
return false;
}
}
function isEmailValid() {
var str = document.getElementById("EmailTB").value;
var lastAtPos = str.lastIndexOf('#');
var lastDotPos = str.lastIndexOf('.');
var isFine = (lastAtPos < lastDotPos && lastAtPos > 0 && str.indexOf('##') == -1 && lastDotPos > 2 && (str.length - lastDotPos) > 2);
var ValidationLabel=document.getElementById("ValidateEmail");
if(isFine)
{
ValidationLabel.style.display='none';
return true;
}
else
{
ValidationLabel.style.display='inline';
return false;
}
}
</script>
<title></title>
<style type="text/css">
.Validators
{
display:none;
}
</style>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Panel id="RegisterRelated" runat="server">
Username:<br />
<asp:TextBox ID="UserTB" runat="server" OnChange="isUserValid()" AutoPostBack="false"></asp:TextBox>
<asp:Label ID="ValidateUser" runat="server" ForeColor="Red"
Text="Username must be 6-15 characters in length, and contain no special characters." CssClass="Validators"></asp:Label>
<br />
Password:<br />
<asp:TextBox ID="PasswordTB" runat="server" OnChange="isPassValid()" AutoPostBack="false"></asp:TextBox>
<asp:Label ID="ValidatePassword" runat="server" ForeColor="Red"
Text="Password must be 6-15 characters in length, and contain no special characters." CssClass="Validators"></asp:Label>
<br />
Confirm password:<br />
<asp:TextBox ID="ConfirmTB" runat="server" OnChange="isConfirmValid()" AutoPostBack="false"></asp:TextBox>
<asp:Label ID="ValidateConfirm" runat="server" ForeColor="Red"
Text="This field must match the password field." CssClass="Validators"></asp:Label>
<br />
Email:<br />
<asp:TextBox ID="EmailTB" runat="server" OnChange="isEmailValid()" AutoPostBack="false"></asp:TextBox>
<asp:Label ID="ValidateEmail" runat="server" ForeColor="Red" Text="Invalid Email." CssClass="Validators"></asp:Label>
<br />
<br />
<asp:Button ID="Register" runat="server" Text="Register" onclick="Register_Click" EnableViewState="false"/>
<br />
<asp:Panel ID="Answer" runat="server" >
</asp:Panel>
</asp:Panel>
<br />
<br />
<asp:Panel id="LoginRelated" runat="server">
User:
<asp:TextBox ID="LoginUserTB" runat="server" AutoPostBack="false"></asp:TextBox>
<br />
Password:
<asp:TextBox ID="LoginPassTB" runat="server" AutoPostBack="false"></asp:TextBox>
<br />
<asp:Button ID="Login" runat="server" Text="Login" onclick="Login_Click" EnableViewState="false" />
<br />
</asp:Panel>
<asp:Panel ID="InPage" runat="server">
<asp:Panel ID="LogAnswer" runat="server">
</asp:Panel>
<br />
<asp:Label ID="WelcomeTag" runat="server"></asp:Label>
<br />
<br />
<asp:Button ID="logout" runat="server" onclick="logout_Click" Text="Logout" EnableViewState="false"/>
</asp:Panel>
</div>
</form>
</body>
</html>
C# Login, Logout & Register buttons:
protected void Register_Click(object sender, EventArgs e)
{
Label Reply = new Label();
if (Session["User"] == null)
{
Result myRegResult = Result.IN_PROG;
User myAddedUser = new User(UserTB.Text, PasswordTB.Text, EmailTB.Text);
DbManager.OpenDbConnection();
myRegResult = DbManager.Register(myAddedUser); //Connection with the database.
Reply.Text = resultToString(myRegResult);
Reply.ForeColor = resultColor(myRegResult);
}
else
{
Reply.Text = "You must log out before you register.";
Reply.ForeColor = resultColor(Result.EXEC_ERROR);
}
Answer.Controls.Add((Control)Reply);
//Reset_Fields();
}
protected void Login_Click(object sender, EventArgs e)
{
Label Reply = new Label();
LoginProc Status = LoginProc.IN_PROG;
DbManager.OpenDbConnection();
Status = DbManager.Login(LoginUserTB.Text, LoginPassTB.Text); //Connection with the database
Reply.Text = ProcToString(Status);
Reply.ForeColor = ProcToColor(Status);
LogAnswer.Controls.Add(Reply);
if (Status == LoginProc.FINE)
Session["User"] = new User(LoginUserTB.Text, LoginPassTB.Text, null);
//Reset_Fields();
}
protected void logout_Click(object sender, EventArgs e)
{
Session["User"] = null;
}
Page load:
protected void Page_Load(object sender, EventArgs e)
{
if (Session["User"] != null)
{
RegisterRelated.Visible = false;
LoginRelated.Visible = false;
InPage.Visible = true;
WelcomeTag.Text = "Welcome, " + ((User)Session["User"]).Username + ".";
}
else
{
RegisterRelated.Visible = true;
LoginRelated.Visible = true;
WelcomeTag.Text = String.Empty;
InPage.Visible = false;
}
}
EDIT: A friend of mine adviced me to take a look in the ASP.NET page lifecycle, and it might have something to do with the database interactions being done after the page is presented, if it helps anyone.
Your friend is correct, you need to understand the page the Page Life cycle better. Basically in this instance you need to understand that the OnLoad event happens before any click events. You can see this for yourself by adding a break point to the OnLoad event and the click handler. You will see that the order of events as they happen.
In this instance I would writ a method to set up the page, and then call this in each of the on click events
private void setUpPage()
{
if (Session["User"] != null)
{
RegisterRelated.Visible = false;
LoginRelated.Visible = false;
InPage.Visible = true;
WelcomeTag.Text = "Welcome, " + ((User)Session["User"]).Username + ".";
}
else
{
RegisterRelated.Visible = true;
LoginRelated.Visible = true;
WelcomeTag.Text = String.Empty;
InPage.Visible = false;
}
}
protected void Page_Load(object sender, EventArgs e)
{
//Call if not in response to button click
if(!IsPostBack)
{
setUpPage();
}
}
protected void Register_Click(object sender, EventArgs e)
{
Label Reply = new Label();
if (Session["User"] == null)
{
Result myRegResult = Result.IN_PROG;
User myAddedUser = new User(UserTB.Text, PasswordTB.Text, EmailTB.Text);
DbManager.OpenDbConnection();
myRegResult = DbManager.Register(myAddedUser); //Connection with the database.
Reply.Text = resultToString(myRegResult);
Reply.ForeColor = resultColor(myRegResult);
}
else
{
Reply.Text = "You must log out before you register.";
Reply.ForeColor = resultColor(Result.EXEC_ERROR);
}
Answer.Controls.Add((Control)Reply);
//Reset_Fields();
//Reset the fields as required AFTER you have done what you need with the database
setUpPage();
}
protected void Login_Click(object sender, EventArgs e)
{
Label Reply = new Label();
LoginProc Status = LoginProc.IN_PROG;
DbManager.OpenDbConnection();
Status = DbManager.Login(LoginUserTB.Text, LoginPassTB.Text); //Connection with the database
Reply.Text = ProcToString(Status);
Reply.ForeColor = ProcToColor(Status);
LogAnswer.Controls.Add(Reply);
if (Status == LoginProc.FINE)
Session["User"] = new User(LoginUserTB.Text, LoginPassTB.Text, null);
//Reset_Fields();
//Reset the fields as required AFTER you have done what you need with the database
setUpPage();
}
protected void logout_Click(object sender, EventArgs e)
{
Session["User"] = null;
//Reset the fields as required AFTER you have done what you need with the database
setUpPage();
}
When you click the login or register button, page load event works firstly, and after button click event works.
I can see that, you set to page display in page load event and set to Session value in button click event. So at first click, page load event triggered first, but there is no Session value yet. Page load event finishes and resume with button click event, so Session value is not null now (if entered user info is valid).
It is the reason why page work at second click.
Solution:
protected void Page_Load(object sender, EventArgs e)
{
if (this.IsPostBack) //just write this
return;
if (Session["User"] != null)
{
RegisterRelated.Visible = false;
LoginRelated.Visible = false;
InPage.Visible = true;
WelcomeTag.Text = "Welcome, " + ((User)Session["User"]).Username + ".";
}
else
{
RegisterRelated.Visible = true;
LoginRelated.Visible = true;
WelcomeTag.Text = String.Empty;
InPage.Visible = false;
}
}
Note: I got your code and tried.
Also see this: http://msdn.microsoft.com/en-us/library/ms178472%28v=vs.85%29.aspx
I think there is issue with validators. Please set causes validation property of buttons according to your requirements.
Try Page_BlockSubmit = false; before every return false;
From the title above, my code at the first time page_load, there is no problem, it show correctly but after I click button to change language, it is disappear(only show header). I spend about one week to find out but still cannot find what happen.
If the visible data MORE than 1, its working properly.
EDIT:
Forgot to put my page Load method
protected void Page_Load(object sender, EventArgs e)
{
NoResult.Visible = false;
Get_Data();
}
protected void Get_Data()
{
DBCAD.Service1 myCADDB = new DBCAD.Service1();
myCADDB.UseDefaultCredentials = true;
string result = "";
//set web service proxy
if (!GlobalVariable_CCCNS.filterOrNot)
{
//invoke web service method
result = myCADDB.CallCardStatus_Filter_CCCNSEMBILAN_ALL();
}
else
{
GlobalVariable_CCCNS.FilterDC = DropDownList1.SelectedValue;
//invoke web service method
if (GlobalVariable_CCCNS.FilterDC == "CCC NS ALL")
{
result = myCADDB.CallCardStatus_Filter_CCCNSEMBILAN_ALL();
}
else
{
result = myCADDB.CallCardStatus_Filter(GlobalVariable_CCCNS.FilterDC);
}
}
//read the response data and put in xml document
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.LoadXml(result);
string mypath = Server.MapPath(#"Data.xml");
//XmlTextReader reader = new XmlTextReader ("DBCAD.xml");
xmlDoc.Save(mypath);
//set the data set
DataSet ds = new DataSet();
ds.ReadXml(mypath);
//Open hidden column
CallCardStatus.Columns[0].Visible = true;
if (ds.Tables.Count > 0)
{
//list out the result to Data Grid
CallCardStatus.DataSource = ds;
CallCardStatus.DataBind();
}
else
{
NoResult.Visible = true;
}
//Clear Unwanted Column
CallCardStatus.Columns[0].Visible = false;
}
Here is my RowDataBound
string lastRow = "";
protected void CallCardStatus_RowDataBound(object sender, GridViewRowEventArgs e)
{
//Many item with same id but different status, I just want to visible and get the first row for each id.
if (e.Row.RowType == DataControlRowType.DataRow)
{
var thisRow = e.Row;
if (thisRow.Cells[0].Text == lastRow)
{
e.Row.Visible = false;
}
lastRow = thisRow.Cells[0].Text;
}
}
Here is my RadioButton for Language Malay and English
protected void RadioButtonList1_SelectedIndexChanged(object sender, EventArgs e)
{
GlobalVariable_CCCNS.cultureName = RadioButtonList1.SelectedValue.ToString();
Page.Culture = GlobalVariable_CCCNS.cultureName;
Page.UICulture = GlobalVariable_CCCNS.cultureName;
if (GlobalVariable_CCCNS.cultureName == "ms-MY")
{
Label2.Visible = false;
Label2.Text = "Kawalan Status Kad Panggilan";
Label2.Visible = true;
}
else
{
Label2.Visible = false;
Label2.Text = "CallCard Status Monitoring";
Label2.Visible = true;
}
Page_Render();
}
protected void Page_Render()
{
Page.Culture = GlobalVariable_CCCNS.cultureName;
Page.UICulture = GlobalVariable_CCCNS.cultureName;
ALL.Text = GetLocalResourceObject("ALLResource1.Text").ToString();
Label1.Text = GetLocalResourceObject("Label1Resource1.Text").ToString();
NoResult.Text = GetLocalResourceObject("NoResultResource1.Text").ToString();
DBCAD.Service1 myCADDB = new DBCAD.Service1();
myCADDB.UseDefaultCredentials = true;
string result = "";
//set web service proxy
if (!GlobalVariable_CCCNS.filterOrNot)
{
//invoke web service method
result = myCADDB.CallCardStatus_Filter_CCCNSEMBILAN_ALL();
}
else
{
GlobalVariable_CCCNS.FilterDC = DropDownList1.SelectedValue;
//invoke web service method
if (GlobalVariable_CCCNS.FilterDC == "CCC NS ALL"){
result = myCADDB.CallCardStatus_Filter_CCCNSEMBILAN_ALL();
}else{
//invoke web service method
result = myCADDB.CallCardStatus_Filter(GlobalVariable_CCCNS.FilterDC);
}
}
//read the response data and put in xml document
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.LoadXml(result);
string mypath = Server.MapPath(#"Data.xml");
//XmlTextReader reader = new XmlTextReader ("DBCAD.xml");
xmlDoc.Save(mypath);
//set the data set
DataSet ds = new DataSet();
ds.ReadXml(mypath);
// CallCardStatus.DataSource = ds;
//CallCardStatus.DataBind();
//Open hidden column
CallCardStatus.Columns[0].Visible = true;
if (ds.Tables.Count > 0)
{
//list out the result to Data Grid
CallCardStatus.DataSource = ds;
CallCardStatus.Columns[2].HeaderText = GetLocalResourceObject("ButtonFieldResource1.Text").ToString();
CallCardStatus.Columns[3].HeaderText = GetLocalResourceObject("BoundFieldResource3.HeaderText").ToString();
CallCardStatus.Columns[4].HeaderText = GetLocalResourceObject("BoundFieldResource4.HeaderText").ToString();
CallCardStatus.Columns[5].HeaderText = GetLocalResourceObject("BoundFieldResource5.HeaderText").ToString();
CallCardStatus.Columns[6].HeaderText = GetLocalResourceObject("BoundFieldResource6.HeaderText").ToString();
CallCardStatus.Columns[7].HeaderText = GetLocalResourceObject("BoundFieldResource7.HeaderText").ToString();
CallCardStatus.Columns[8].HeaderText = GetLocalResourceObject("BoundFieldResource8.HeaderText").ToString();
CallCardStatus.Columns[9].HeaderText = GetLocalResourceObject("BoundFieldResource9.HeaderText").ToString();
CallCardStatus.DataBind();
}
else
{
NoResult.Visible = true;
}
//Clear Unwanted Column
CallCardStatus.Columns[0].Visible = false;
}
Anyone can help?Thanks..Siti..:)
In order to clean up your legacy code a little bit, I recommend you the following: (cleaning your code will help u to spot the error easier)
Binding your GridView
The best practice to bind a data-bound control is inside the Page_Load event:
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
// in this method u will bind your GridView
this.BindGrid();
}
}
Unless I'm missing something, the code inside the Page_Render method is used to render your GridView, and that code is duplicated in the Get_Data method. You could place the code specific to bind your GridView inside one single method.
Now you only need to re-bind your GridView when its content has changed, for example if you allow your users to edit your GridView records. Otherwise, you should not re-bind it. (This is true, as long as your page has EnableViewState="true")
The code to localize your GridView columns can be moved to the GridVew.DataBound event. Or even better, delegate the logic to localize the view to your markup, to do it, you could create templated columns in your GridView.
Example:
<asp:GridView runat="server" DataSourceID="lds" ID="gv"
AutoGenerateColumns="false"
>
<Columns>
<asp:TemplateField>
<HeaderTemplate>
<asp:Label Text="<%$ Resources: your_resource_file_name_without_extension, your resource_key %>" runat="server" />
</HeaderTemplate>
<ItemTemplate>
<asp:Label ID="a_meaningfull_name" Text='<%# Eval("your_field_name") %>' runat="server" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Set the page language overriding the Page.InitializeCulture method:
Note that you only need to set this.UICulture = culture; and this.Culture = culture; inside this method
protected override void InitializeCulture()
{
// you have to call Request.Form, because at this point in the page life cycle, the page viewstate has not been loaded yet
var culture = this.Request.Form["RadioButtonList1"];
if (!string.IsNullOrWhiteSpace(culture))
{
// if the values of your list are culture specific (ie. en-US, es-MX, etc) you can uncomment the following line
// this.Culture = culture;
this.UICulture = culture;
base.InitializeCulture();
}
}
Using this approach you do not need the RadioButtonList1_SelectedIndexChanged event. The code you are placing inside this event won't be necessary.
This code:
if (GlobalVariable_CCCNS.cultureName == "ms-MY")
{
Label2.Visible = false;
Label2.Text = "Kawalan Status Kad Panggilan";
Label2.Visible = true;
}
else
{
Label2.Visible = false;
Label2.Text = "CallCard Status Monitoring";
Label2.Visible = true;
}
Can be easily eliminated using markup: (note that you will need to create one resource file for each language you want to use in your application, to learn more about ASP.Net Globalization click here)
Using global resources
<!-- Assuming global resources -->
<asp:Label runat="server" ID="Label2" Text="<%$ Resources: your_resource_file_name_without_extension, your_resource_key %>" />
Your global resource file would look like:
<data name="your_resource_key" xml:space="preserve">
<value>your text</value>
</data>
Using local resources
<!-- Assuming local implicit resources -->
<asp:Label runat="server" ID="Label2" meta:resourcekey="base_name_of_your_resource_key" Text="default value used to render the control at design time in VS" />
In this case, your local resource file would look like:
<data name="base_name_of_your_resource_key.Text" xml:space="preserve">
<value>your text</value>
</data>
You do not need to call Page_Render(); in the RadioButtonList1_SelectedIndexChanged event
I have a FormView that I user for updating a record. There is a link button that when fires should perforom the updating via BLL and DAL. I am not using built-in ODS and I will not condsider using it.
I have all my grids and formviews populated manuualy by calling methods that fetch the data from the database.
For instance my details view is populated like this:
protected void DlMembers_ItemCommand(object source, DataListCommandEventArgs e)
{
if (e.CommandName.ToString() == "Select")
{
DlMembers.Visible = false;
lblError.Text = string.Empty;
lblError.Visible = false;
fvMemberDetail.Visible = true;
fvMemberDetail.ChangeMode(FormViewMode.Edit);
MemberBLL getMemberInfo = new MemberBLL();
int Ident = Convert.ToInt32(e.CommandArgument.ToString());
fvMemberDetail.DataSource = getMemberInfo.GetMemberByIdent(Ident);
fvMemberDetail.DataBind();
}
if (e.CommandName.ToString() == "DeleteSelected")
{
DlMembers.Visible = true;
lblError.Text = string.Empty;
lblError.Visible = false;
fvMemberDetail.Visible = false;
fvMemberDetail.ChangeMode(FormViewMode.ReadOnly);
}
What I want to do if to capature my linkbutton on click event and do this (except that the runtime never reaches this method):
protected void MemberInfoUpdating(object sender, EventArgs e)
{
TextBox id = (TextBox)fvMemberDetail.FindControl("txtIdent");
if (id.Text != string.Empty || id.Text != "")
{
TextBox txtFN = (TextBox)fvMemberDetail.FindControl("txtFN");
TextBox txtLN = (TextBox)fvMemberDetail.FindControl("txtLN");
DropDownList ddlAddress = (DropDownList)fvMemberDetail.FindControl("ddlAddress");
TextBox txtEmail = (TextBox)fvMemberDetail.FindControl("txtEmail");
TextBox txtHPhone = (TextBox)fvMemberDetail.FindControl("txtHPhone");
TextBox txtWPhone = (TextBox)fvMemberDetail.FindControl("txtWPhone");
TextBox txtMPhone = (TextBox)fvMemberDetail.FindControl("txtMPhone");
DropDownList ddlPos = (DropDownList)fvMemberDetail.FindControl("ddlPos");
DropDownList ddlIsAdmin = (DropDownList)fvMemberDetail.FindControl("ddlIsAdmin");
bool blIsAdmin = false;
if (ddlIsAdmin.SelectedValue == "True") blIsAdmin = true;
TextBox txtComments = (TextBox)fvMemberDetail.FindControl("txtComments");
MemberBLL updateMemberInfo = new MemberBLL();
bool UpdateOK = updateMemberInfo.UpdateMemberByIdent(
txtFN.Text,
txtLN.Text,
ddlAddress.SelectedValue,
txtEmail.Text,
txtHPhone.Text,
txtWPhone.Text,
txtMPhone.Text,
blIsAdmin,
txtComments.Text,
Convert.ToInt32(ddlPos.SelectedValue),
Convert.ToInt32(id.Text));
}
else
{
//Display error - no user id cannot update record
}
}
The linkbutton looks like this:
<asp:LinkButton ID="UpdateButton" runat="server" CausesValidation="True"
OnClick="MemberInfoUpdating" Text="Update" />
Where is this LinkButton? If it's inside a FormView template, then you'll likely need to use something like this instead:
<asp:LinkButton ID="UpdateButton" runat="server" CommandName="Update" Text="Update" />
Then handle the "Update" command in DlMembers_ItemCommand.
Alternatively, attach your code to the OnItemUpdating event of the FormView rather than some extra event you don't need:
<asp:FormView ID="fvMemberDetail" runat="server" OnItemUpdating="MemberInfoUpdating">