Reputation: 77
I have a control that should prompt the user to choose either the session's customerId or the page's old viewstate customerId. To do this the control has a validate in the code behind based on
On postback, how can I add a error message to validation summary?
When is step through the code I see the err.IsValid is set to false. But when I get to Page.IsValid and look at the validators it is set to true. Any information that can be provided to help me understand why this is not proceeding as I expect would be appreciated.
code behind
public partial class CustomerChanged : System.Web.UI.UserControl
{
protected override void OnInit(EventArgs e)
{
base.OnInit(e);
this.Page.PreLoad += Page_PreLoad;
}
void Page_PreLoad(object sender, EventArgs e)
{
if (!IsPostBack)
{
ViewState.Add("CustID", Globals.CurrentCust.CustId);
}
if (IsPostBack)
{
if (Convert.ToInt32(ViewState["CustID"]) != Globals.CurrentCust.CustId)
{
btnOldCustId.Text = "Old CustID \n" + ViewState["CustID"].ToString();
btnNewCustId.Text = "New CustID \n" + Globals.CurrentCust.CustId.ToString();
btnOldCustId.OnClientClick = string.Format("return changeCustomer({0},'{1}');", ViewState["CustID"].ToString(), Globals.GeneralSiteUrl);
System.Web.UI.WebControls.CustomValidator err = new System.Web.UI.WebControls.CustomValidator();
err.IsValid = false;
err.ErrorMessage = "The customer has changed.";
Page.Validators.Add(err);
}
}
}
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack)
{
Page.Validate();
if (!Page.IsValid)
{
ScriptManager.RegisterStartupScript(this, this.GetType(), "CustomerChangedModalDialog", "ShowCustomerChangedModalDialog();", true);
}
}
}
protected void btnNewCustId_Click(object sender, EventArgs e)
{
Response.Redirect(Request.RawUrl);
}
}
Upvotes: 1
Views: 6476
Reputation: 5318
You can add an error message to the validation summary using the following:
if (IsPostBack)
{
Page.Validate();
var valid = CustomValidate();
if(valid && Page.IsValid)
{
}
}
protected bool CustomValidate()
{
var valid = true;
///do your validation here
var validator = new CustomValidator();
validator.IsValid = false;
valid = validator.IsValid;
Validator.ErrorMessage = "Error....";
this.Page.Validators.Add(validator);
return valid;
}
Upvotes: 2