The ControlToValidate property of 'NameValid' cannot be blank - asp.net

i m writing a web application and i have a problem in one on my pages!
i design a admin page and i want to log in before user enter in this page!
there are three RequiredFieldValidator and a button(AddButton) in my page and i want to check the fields when user click the button but when the page is loaded the validation is checked and visual studio throw a exception:
"The ControlToValidate property of 'NameValid' cannot be blank" NameValid is one of my Validation controls in page!
and another question: what is the advantage of (using) block when you work with databases and files?
my class is here:
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (Request.UrlReferrer == null)
{
//a page for log in
Response.Redirect("~/LogIn.aspx");
}
}
protected void Page_Error(object sender, EventArgs e)
{
Response.Clear();
Response.Write("<h2>Exception</h2><br />");
Response.Write(Server.GetLastError().Message);
Server.ClearError();
}
protected void AddButton_Click(object sender, EventArgs e)
{
const string ConnectionString = #"Data Source=.\SQLEXPRESS;AttachDbFilename=D:\rasoul\sourcecode\ASP-PROJECTS\UniversityDataBase\DataBase\PersonDataBase.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True";
using (SqlConnection con=new SqlConnection(ConnectionString))
{
string ID = IDField.Text.Trim();
string Name = NameField.Text.Trim();
string LastName = LastNameField.Text.Trim();
DataSet data = new DataSet();
SqlCommand cmd = con.CreateCommand();
cmd.CommandText = String.Format("insert into StudentTable values('{0}','{1}','{2}')", ID, Name, LastName);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
}
}
what should i do?

In required field validators you MUST specify the ControlToValidate - the control you which to validate that it is required.
MSDN Description - Use the ControlToValidate property to specify the input control to validate. This property must be set to the ID of an input control for all validation controls except the CustomValidator control, which can be left blank. If you do not specify a valid input control, an exception will be thrown when the page is rendered. (Source: http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.basevalidator.controltovalidate.aspx)
The advantage of the using block is it ensures the correct use of IDisposable objects.
using (Font font1 = new Font("Arial", 10.0f))
{
byte charset = font1.GdiCharSet;
}
is equivalent to
{
Font font1 = new Font("Arial", 10.0f);
try
{
byte charset = font1.GdiCharSet;
}
finally
{
if (font1 != null)
((IDisposable)font1).Dispose();
}
}
Source: http://msdn.microsoft.com/en-us/library/yh598w02.aspx

you have to check controltovalidate. you have to assign controller.

Related

CheckedItems.Count Always Returns a Value of Zero (0)

I have Use telerik:radcombobox with mutiple select value.I have bind data LoadOndemand.All Work Fine but when i click on submit button then CheckedItems.Count=0.
Thank you,
Dhiren Patel
I believe you are using EnableLoadOnDemand property of the RadComboBox. RadComboBox items are not accessible on the server-side when loading them on demand and therefore always return CheckedItems as well as SelectedItems count as zero and this is a known issue. This is because RadComboBox items loaded on demand using the ItemsRequested event handler or WebService do not exist on the server and cannot be accessed using the server-side FindItemByText / Value methods. SelectedItem and SelectedIndex properties are always Null / Nothing. This is needed for speed (otherwise the combobox will not be that responsive upon each keypress if state information and ViewState were persisted).
Please have a look at the following code without using load on demand which works fine at my end.
<telerik:RadComboBox runat="server" ID="RadComboBox1" CheckBoxes="true">
</telerik:RadComboBox>
<br />
<br />
<telerik:RadButton ID="RadButton1" runat="server" Text="Get Count" OnClick="RadButton1_Click">
</telerik:RadButton>
Code Behind:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
populateRadCombobox("select ContactName from Customers");
}
}
protected void populateRadCombobox(string query)
{
String ConnString =
ConfigurationManager.ConnectionStrings["NorthwindConnectionString"].ConnectionString;
SqlConnection conn = new SqlConnection(ConnString);
SqlDataAdapter adapter = new SqlDataAdapter();
adapter.SelectCommand = new SqlCommand(query, conn);
DataTable myDataTable = new DataTable();
conn.Open();
try
{
adapter.Fill(myDataTable);
RadComboBox1.DataTextField = "ContactName";
RadComboBox1.DataSource = myDataTable;
RadComboBox1.DataBind();
}
finally
{
conn.Close();
}
}
protected void RadButton1_Click(object sender, EventArgs e)
{
if (RadComboBox1.CheckedItems.Count > 0)
{
//business logic goes here
}
else
{
}
Reference:
http://www.telerik.com/forums/checkeditems-count-always-returns-a-value-of-zero-0
http://www.telerik.com/forums/radcombobox-losing-client-selections-on-postback

Not able to get value of dropdownlist.selectedvalue on SelectedIndexChanged

After much much research I cannot find the same problem anywhere, under my circumstances. I've enabled viewstate at the page, control, and individual dropdown levels. Page_Load only loads the dropdown if PostBack true according to code.
The problem is that on postback (triggered by the DropDownList or any control), "Empty Parameter" shows in my debugging label, which tells me it's not grabbing the SelectedValue from the dropdown in its selectedIndexChanged method. Also, my dropdowns reset to their initial value before the PageLoad "PopulateFilterDropdowns" method.
Any ideas? I've been searching here, google, anywhere and everywhere I can go. Everybody's problem is usually a lack of "IsPostback" or EnableViewState="true", but no dice on my end. I will mention this is a ascx UserControl, inside of a page with a MasterPage. But I believe the code of each of those is irrelevant to this problem, and quite large to post here.
Help!?
Dropdown:
<asp:DropDownList ID="ddlTopics" runat="server" EnableViewState="true" AutoPostBack="true" OnSelectedIndexChanged="ddlTopics_SelectedIndexChanged">
<asp:ListItem Text="Topic" Value=""></asp:ListItem>
</asp:DropDownList>
Page_Load:
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
PopulateFilterDropdowns();
}
}
Following methods:
public void PopulateFilterDropdowns()
{
PopulateTopicDropdown();
PopulateAssetTypeDropdown();
PopulateLevelDropdown();
}
public void PopulateTopicDropdown()
{
using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["XXX"].ConnectionString))
{
conn.Open();
using (SqlCommand cmd = new SqlCommand("StoredProc", conn))
{
cmd.CommandType = CommandType.StoredProcedure;
using (SqlDataReader rdr = cmd.ExecuteReader())
{
while (rdr.Read())
{
//ListItem itm = new ListItem();
//itm.Value = rdr[0].ToString();
//itm.Text = rdr[0].ToString();
ddlTopics.Items.Add(new ListItem(rdr[0].ToString(), rdr[0].ToString()));
}
}
}
}
}
Problem zone:
protected void ddlTopics_SelectedIndexChanged(object sender, EventArgs e)
{
DropDownList ddlTopics1 = (DropDownList)sender;
string topic = ddlTopics1.SelectedValue;
if (String.IsNullOrEmpty(topic))
lblDebug.Text = "Empty Parameter";
else
lblDebug.Text = topic;
//PopulateRecordsByTopic(topic);
}
public void PopulateRecordsByTopic(string topic)
{
//Query and Binding of repeater on page
}

How to declare public variable from protected method in asp net?

I have database with images in folder on my server. To display this images I'am using DataList control. ItemTemplate include also a LinkButton
<asp:LinkButton ID="wybierzZdjecieBtn" OnClick="choosePhotoButton_Click" CommandArgument='<%#Eval("PhotoLinkAddress")%>' CssClass="wybierzZdjecieButton" runat="server">Choose photo</asp:LinkButton>
To receiving Value from LinkButton CommandArgument i'am using this method:
protected void choosePhotoButton_Click(object sender, EventArgs e)
{
LinkButton button = (LinkButton)(sender);
string photoLinkAddressVar = button.CommandArgument.ToString();
Response.Write(PhotoLinkAddressVar);
}
This works fine, no problems. But this is not what I want achieve. My intentions is send this variable "PhotoLinkAddressVar" to this method:
protected void addNewNews_Click(object sender, EventArgs e)
{
string trescStatus = "czeka";
string autor = Session["userName"].ToString();
DateTime data = DateTime.Now;
string dataFormat = "";
dataFormat = data.ToString("dd/MM/yyyy H:mm");
string CS = ConfigurationManager.ConnectionStrings["wiadomosciConnection"].ConnectionString;
using (SqlConnection con = new SqlConnection(CS))
{
con.Open();
string dodaj = "Insert into News (TytulNews, TrescNews, Autor, Data, Kategoria, Dotyczy, PhotoLinkAddress, Status) values (#TytulNews, #TrescNews, #Autor, #Data, #Kategoria, #Dotyczy, #PhotoLinkAddress, #Status)";
SqlCommand com = new SqlCommand(dodaj, con);
com.Parameters.AddWithValue("#TytulNews", tytulNewsTextBox.Text);
com.Parameters.AddWithValue("#TrescNews", trescTextBox.Text);
com.Parameters.AddWithValue("#Autor", autor);
com.Parameters.AddWithValue("#Data", dataFormat);
com.Parameters.AddWithValue("#Kategoria", kategoria.SelectedValue.ToString());
com.Parameters.AddWithValue("#Dotyczy", dotyczy.SelectedValue.ToString());
com.Parameters.AddWithValue("#PhotoLinkAddress", photoLinkAddressVar);
com.Parameters.AddWithValue("#Status", trescStatus);
com.ExecuteNonQuery();
}
}
User have to choose photo before press "Add News", because if He doesn't do that, he will receive error message. I dont know, how do that. I Was trying declare some kind public variable before PageLoad and do something like this:
protected void choosePhotoButtonButton_Click(object sender, EventArgs e)
{
LinkButton button = (LinkButton)(sender);
photoLinkAddressVar = button.CommandArgument.ToString();
}
but that method won't declare the variable. Do You have any idea, how can I achieve that ?.
You could use also the ViewState.
protected void choosePhotoButton_Click(object sender, EventArgs e)
{
LinkButton button = (LinkButton)(sender);
string photoLinkAddressVar = button.CommandArgument.ToString();
View["photoLinkAddressVar"]=photoLinkAddressVar;
Response.Write(PhotoLinkAddressVar);
}
Then in the addNewNews_Click method, you coukld retrieve this value with the following way:
com.Parameters.AddWithValue("#PhotoLinkAddress", ViewState["photoLinkAddressVar"]);
For further documantation about ViewState please look here.

How to connect to SQL Server using ADO.Net

This is the first time I'm designing a web site. I'm having problem on connecting to my database. None of buttons work on pages. The most important one is Register button. I fill the form correctly but when I press Register button it doesn't register the new user into database. It even doesn't show any error message which I've considered. For example, it doesn't show that You've registered before or Your registration wasn't successful. No error message and no new record in my database. I've removed the captcha code because I thought that may cause problem.Here's my code:
using System;
using System.Data.SqlClient;
using System.Web.UI.WebControls;
public partial class SignUp : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
string strname = Cache["TF"] as string;
if (strname != null)
{
(Master.FindControl("Lozv") as Label).Text = strname;
(Master.FindControl("LinkButton1") as LinkButton).Visible = true;
}
else
{
(Master.FindControl("Lozv") as Label).Text = "Guest";
(Master.FindControl("LinkButton1") as LinkButton).Visible = false;
}
}
protected void Button1_Click1(object sender, EventArgs e)
{
string username = txtboxUser.Text;
SqlConnection sqlc = new SqlConnection("Data Source=.; Database=LDatabase; Integrated Security=True");
SqlCommand cmd = new SqlCommand("SELECT dbo.CheckUserName(#UN)");
cmd.Parameters.AddWithValue("#UN", txtboxUser.Text);
sqlc.Open();
Boolean User = Convert.ToBoolean(cmd.ExecuteScalar());
sqlc.Close();
if (User == false) ////////////// if user name is not in DB//////////////
{
SqlConnection sqlca = new SqlConnection();
sqlca.ConnectionString = "data source=. ; database=LDatabase ; integrated security=true";
SqlCommand cmda = new SqlCommand();
cmda.Connection = sqlca;
cmda.CommandText = "INSERT INTO User_Pass values(#UserName,#Pass,#Name,#LastName,#Email,#Date,#Sex,'0')";
cmda.Parameters.AddWithValue("#UserName", txtboxUser.Text);
cmda.Parameters.AddWithValue("#Pass", txtboxPass.Text);
cmda.Parameters.AddWithValue("#Name", txtboxName.Text);
cmda.Parameters.AddWithValue("#LastName", txtboxSurname.Text);
cmda.Parameters.AddWithValue("#Email", txtboxEmail.Text);
cmda.Parameters.AddWithValue("#Date", DateTime.Now);
cmda.Parameters.AddWithValue("#Sex", rbtnGender.SelectedValue.ToString());
cmd.Parameters.AddWithValue("#manager", "No");
sqlca.Open();
int n= cmda.ExecuteNonQuery();
if (n <= 0)
LMsg.Text = "Your registration wasn't successful";
else
{
txtboxName.Text = "";
txtboxSurname.Text = "";
txtboxUser.Text = "";
txtboxPass.Text = "";
txtboxRePass.Text = "";
txtboxEmail.Text = "";
rbtnGender.SelectedIndex = -1;
LMsg.Text = "You registered successfully.";
}
sqlca.Close();
}
else //////////////if user name is in db//////////////
{
LMsg.Text = "This username has already registered.";
}
}
}
Does Captcha have anything to do with this type of problem? Any help would be appreciated.
Put your button like this in the aspx-markup:
<asp:Button ID="btnRegister" runat="server" Click="Button1_Click1" Height="26px" Text="register" Width="88px"/>
It should trigger the method.
Edit: Or bind the event in the Page_Load method (remove the Click-attribute from the button first - from my previous example above).
protected void Page_Load(object sender, EventArgs e)
{
btnRegister.Click += new EventHandler(Button1_Click1);
string strname = Cache["TF"] as string;
[...]

How to provide different user pages with same login page for different users?

what i am tryin to do is
i have common login page with 4 users each has different roles
and i have a Singel master pages where i have different contorls.....how to provide authentication to the own page with the contorls assigned to them..regarding on thier role they should be directed to the given page....
user 1 manager he needs only some controls on the page so when he logins the master page should contain only the controls assgned to him
applys the same for all users
can any one help me......planing ,i dont know where to start....
Try This in Button Click
SqlConnection con = new SqlConnection("Integrated Security=SSPI;Persist Security Info=False;Initial Catalog=DebitCareBankApp;Data Source=SSDEV7-HP\\SQLEXPRESS");
string cmdStr = "select LoginType from Login where UserName='" + TxtUserName.Text + "' AND Password = '" + TxtPassword.Text + "'";
SqlCommand cmd = new SqlCommand(cmdStr, con);
con.Open();
Object TypeUser = cmd.ExecuteScalar();
con.Close();
if (TypeUser != null)
{
LblError.Visible = false;
LblError.Text = "";
if (TypeUser.ToString() == "Manager")
{
Response.Redirect("~//Administration/Manager/WorkManagement.aspx");
}
else if (TypeUser.ToString() == "HR")
{
Response.Redirect("~//Administration/Hr/CalculateAndGeneratePayslips.aspx");
}
else if (TypeUser.ToString() == "Employee")
{
Response.Redirect("~//Administration/CallingAgent/TodaysWork.aspx");
}
}
else
{
LblError.Visible = true;
LblError.Text = "Invalid Credentials Entered, Try again";
}
There is simple way for this approach below are the steps you can follow
Keep one default Master Page // ("MasterPage.master")
Add as many master pages according to requirement // "manager.master/Admin.master"
Add the Pages to the default Master page
Add class file in app_code where u can map dynamic masterpage
Add this class in App_Code
public class DynamicPage : System.Web.UI.Page
{
protected override void OnPreInit(EventArgs e)
{
string masterfile = getMasterPageFromDatabase();
if (!masterfile.Equals(string.Empty))
{
base.MasterPageFile = masterfile;
}
base.OnPreInit(e);
}
private string getMasterPageFromDatabase()
{
// check the conditions "manager.master/Admin.master"
return "Admin.master";
}
}
when coming to .cs file for default.aspx.cs it would be "System.Web.UI.Page" replace that with DynamicPage
public partial class _Default : **System.Web.UI.Page**
{
protected void Page_Load(object sender, EventArgs e)
{
}
}
finally it comes like
public partial class _Default : **DynamicPage**
{
protected void Page_Load(object sender, EventArgs e)
{
}
}
rest will happen automatically mapped
hope this helps !!!

Resources