How to declare public variable from protected method in asp net? - 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.

Related

I need a DropDown value that is linked to another page

I have a DropDown List where I have brought the values from my Database using code-behind.
I have added a new value after reading data from source, called ".. Add new skill".
Now when user clicks on that item I need a small page (or rather a new page) to open to add the skills that are not mentioned in the DropDownList.
if (!IsPostBack)
{
SqlConnection myConn = new SqlConnection(#"Data Source=USER-PC\SQLEXPRESS;Initial Catalog=KKSTech;Integrated Security=True");
SqlCommand myCmd = new SqlCommand(
"SELECT SkillName, SkillID FROM Skills", myConn);
myConn.Open();
SqlDataReader myReader = myCmd.ExecuteReader();
//Set up the data binding.
DropDownList1.DataSource = myReader;
DropDownList1.DataTextField = "SKillName";
DropDownList1.DataValueField = "SkillID";
DropDownList1.DataBind();
//Close the connection.
myConn.Close();
myReader.Close();
//Add the item at the first position.
DropDownList1.Items.Insert(0, "..Add New Skill");
}
This is my code-behind file.. How do I link that now?
You should use the SelectedIndexChanged event and SelectedValue property:
void ddl_SelectedIndexChanged(object sender, EventArgs e)
{
if(String.Compare(ddl.SelectedValue,"..Add New Skill",true)==0)
Response.Redirect("Add_New_Skill.aspx");
}
Add a SelectedIndexChanged event handler to that dropdown like this
void ddl_SelectedIndexChanged(object sender, EventArgs e)
{
if(ddl.SelectedIndex == 0)
Response.Redirect("Add_New_Skill.aspx");
}
If you want position of "...Add new skill" to be at last of the list
Use this
ddl.Items.Insert(ddl.Items.Count, "...Add New Skill");
Now to redirect to another page you should do this
void ddl_SelectedIndexChanged(object sender, EventArgs e)
{
if(ddl.SelectedIndex == ddl.Items.Count-1)
Response.Redirect("Add_New_Skill.aspx");
}
Set AutoPostBack to true. That way when the user changes an option, it will automatically post the page to the server.
Handle this SelectedIndexChanged event, and redirect to your add page there.
Take your user to a add page.
Add the details to the database.
Bring the user back to this page.
List will be reloaded from database, and you till get your value.
No special linking is required.
This is working
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
bindDropdownlist()
}
}
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
string getvalue = DropDownList1.SelectedItem.Value;
if (getvalue == "..Add New Skill")
{
Response.Redirect("Default.apsx");
}
}
public void bindDropdownlist()
{
SqlDataAdapter dap = new SqlDataAdapter("select coloumn1,colum2 from table", con);
DataSet ds = new DataSet();
dap.Fill(ds);
DropDownList1.DataSource = ds.Tables[0];
DropDownList1.DataTextField = "coloumn1";
DropDownList1.DataValueField = "colum2 ";
DropDownList1.DataBind();
DropDownList1.Items.Insert(0, "..Add New Skill");
}
}
<div>
<asp:DropDownList ID="DropDownList1" runat="server" AutoPostBack="True"
onselectedindexchanged="DropDownList1_SelectedIndexChanged">
</asp:DropDownList>
</div>

How to select Listbox value in asp.net

I have a ListBox in my webpage that is bound from database in this way:
ListBox1.DataTextField = "Text";
ListBox1.DataValueField = "MenuID";
ListBox1.DataSource = SqlHelper.ExecuteReader(DAL.DALBase.ConnectionString, "GetMenu");
ListBox1.DataBind();
I want to get selected item value and used this code but have a error and does not worked.
ListBox1.SelectedValue;
Forgive me if I have problems on how to write because my English is not good.
Can you be more specific on the error you are getting?
Using ListBox1.SelectedValue should work.
For example:
int mySelectedValue = int.Parse(ListBox1.SelectedValue);
or
string mySelectedValue = ListBox1.SelectedValue;
Edit
Added code to ensure the original poster was keeping values in ListBox databound.
protected void Page_Load( object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
BindListBox();
}
}
private BindListBox()
{
ListBox1.DataTextField = "Text";
ListBox1.DataValueField = "MenuID";
ListBox1.DataSource = SqlHelper.ExecuteReader(DAL.DALBase.ConnectionString, "GetMenu");
ListBox1.DataBind();
}
protected void SomeButton_Click( object sender, EventArgs e)
{
string mySelectedValue = ListBox1.SelectedValue;
}

Call a button_click on page_load asp.net

I have a search textbox and a search button, when clicked displays a grid with the following names and gender.However I have redirected the page to another page on edit.Now When I comeback from that page to the page containing the gridview I want to display the same search again. I have successfully put retrieved the information but storing it into session, but I'm not able to call my btn_click event # page_Load.
Here's a snippet:
EDIT: I have made some changes in my code
protected void Page_Load(object sender, EventArgs e)
{
if (Session["Redirected"] != null)
{
if (Session["FirstName"] != null)
txtSearch.Text = Session["FirstName"].ToString();
if (Session["Gender"] != null)
ddlGen.SelectedValue = Session["Gender"].ToString();
btnSearch_Click(sender, e);
}
if (!Page.IsPostBack)
{
BindGrid();
}
}
and here's the click event:
protected void btnSearch_Click(object sender, EventArgs e)
{
string query = "Select EmployeeId,FirstName,Password,Address,sex,Deptno,act_book,actTV,DOJ,isActiveYN from employees where 1=1";
if (txtSearch.Text != "")
{
query += " and FirstName like '%" + txtSearch.Text + "%'";
Session["FirstName"] = txtSearch.Text;
}
if (ddlGen.SelectedValue != "")
{
query += " and sex='" + ddlGen.SelectedValue.ToUpper() + "'";
Session["Gender"] = ddlGen.SelectedValue;
}
DataSet ds = new DataSet("Employees");
SqlConnection con = new SqlConnection("Password=admin;User ID=admin;Initial Catalog=asptest;Data Source=dbsvr");
SqlDataAdapter da = new SqlDataAdapter(query, con);
da.Fill(ds);
gvSession.DataSource = ds;
gvSession.DataBind();
}
Now I'm able to save search, so that problem is resolved ,but another has poped up that when I click the button search after changin text it takes me back to the older search..The reason is probably because sessions are not cleared,but I did that as well by handling textchanged and selectedindexchanged eventd.
Rather than trying to call your button click handler from the Page_Load, change your button click handler to simply call another method like:
protected void btnSearch_Click(object sender, EventArgs e)
{
RunSearch();
}
Then move all your btnSearch_Click() code into RunSearch()
Then in your Page_Load you can do something like:
protected void Page_Load(object sender, EventArgs e)
{
if (Session["Gender"] != null && Session["FirstName"] != null)
{
txtSearch.Text = Session["FirstName"].ToString();
ddlGen.SelectedValue = Session["Gender"].ToString();
RunSearch();
}
if (!Page.IsPostBack)
{
BindGrid();
}
}
On a side note, I would recommend taking a look into SQLCommand Parameters. Your code is prone to SQL Injection Attacks:
http://en.wikipedia.org/wiki/SQL_injection
You should reset the session redirected variable so it doesn't fall in the same case.
protected void Page_Load(object sender, EventArgs e)
{
if (Session["Redirected"] != null)
{
Session["Redirected"] = null;
....
You can do using an QueryString paremeter when page return back to main page then here you can check QueryString paremeter is exist. here you can implement code for bind grid
if (Request.QueryString["Back"]!= null)
{
// Your bind grid function
}
You can create a function, which will called both from the button_click and page_load.

The ControlToValidate property of 'NameValid' cannot be blank

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.

problem in updating the textbox data into SQLSERVER

I have problem in updating user profile through asp:TextBox.
At the time of page load , all the textboxes get loaded with correct values from the database sqlserver.
say First name=SAM {i.e SAM is shown in txtName's textfield)
and Last Name=Berton
but when i alter the content of txtName to SAMANTHA
and similary for other textboxes, and click on update profile button, Internally txtName.text="SAM" gets retained notwithstanding the changed content of txtName.text="SAMANTHA" by manually altering the content of textbox.So same value that is "SAM" gets stored into the sqlserver rather than "SAMANTHA".
protected void Page_Load(object sender, EventArgs e)
{
loadProfileData();
}
protected void loadProfileData()
{
string connStringProfileload = ConfigurationManager.ConnectionStrings["myconnString"].ConnectionString;
SqlConnection conProfLoad = new SqlConnection(connStringProfileload);
conProfLoad.Open();
string emailAddLogin = User.Identity.Name.ToString();
string strSqlProfileLoad = "SELECT * FROM [gen_profile] WHERE [email]=#email";
SqlCommand cmd = new SqlCommand(strSqlProfileLoad, conProfLoad);
cmd.Parameters.AddWithValue("#email", emailAddLogin);
SqlDataReader drProfileLoad = cmd.ExecuteReader();
while (drProfileLoad.Read())
{
txtName.Text = drProfileLoad["fname"].ToString();
txtLastName.Text=drProfileLoad["lname"].ToString();
}
drProfileLoad.Close();
conProfLoad.Close();
}
protected void BtnUpdtProf_Click(object sender, EventArgs e)
{
string connStringProfileUpdate = ConfigurationManager.ConnectionStrings["myconnString"].ConnectionString;
SqlConnection conUpdateProf = new SqlConnection(connStringProfileUpdate);
conUpdateProf.Open();
string emailAddLogin = User.Identity.Name.ToString();
string strSqlUpdateProf = "UPDATE gen_profile SET fname =#fname, lname =#lname where email=#email;";
SqlCommand cmdUpdate = new SqlCommand(strSqlUpdateProf, conUpdateProf);
cmdUpdate.Parameters.AddWithValue("#fname", txtName.Text.ToUpper().Trim());
cmdUpdate.Parameters.AddWithValue("#lname", txtLastName.Text.ToUpper().Trim());
cmdUpdate.Parameters.AddWithValue("#email", emailAddLogin);
int i = cmdUpdate.ExecuteNonQuery();
conUpdateProf.Close();
if (i == 1)
Response.Redirect("~/prof/resp_update_prof.aspx");
}
Change this method :
protected void Page_Load(object sender, EventArgs e) {
loadProfileData();
}
to :
protected void Page_Load(object sender, EventArgs e) {
if (!IsPostBack) loadProfileData();
}
Basically, your textBox values are being reset in the page load event, so everytime your page posts back, it's resetting the values in the textboxes and then saving them back to the database.
This is because before your button click event, page_load get's fired which re-populates the textbox.
You can stop this happening by checking for a post back as follows:
protected void Page_Load(object sender, EventArgs e) {
if (!IsPostBack)
{
loadProfileData();
}
}

Resources