Dropdown value is not getting save in ViewState - c#

I have saved the dropdown value in db and in the viewstate, but on page load it is not getting loaded.
Can someone please tell me where am I going wrong
protected void Page_Load(object sender, System.EventArgs e)
{
if (ViewState["ddSelectedValue"] != "0")
{
dd_RuleFor.SelectedValue = Convert.ToInt32(ViewState["ddSelectedValue"]).ToString();
}
}
protected void btn_Save_Click(object sender, System.EventArgs e)
{
if(chkRuleApprover.Checked == true && dd_RuleFor.SelectedValue != "0")
{
strSQL = "update UserFile set Rule_Approval_Selection=" + dd_RuleFor.SelectedItem.Value + " where UID=" + intUserID;
objCmd = new System.Data.SqlClient.SqlCommand(strSQL, oconn);
objCmd.ExecuteNonQuery();
ViewState["ddSelectedValue"] = dd_RuleFor.SelectedValue.ToString();
}
}

Make sure you are filling the dropdown with the values first on pageload and after than use below condition:
if(!Page.Ispostback())
{
if (ViewState["ddSelectedValue"] != "0")
{
dd_RuleFor.SelectedValue = Convert.ToInt32(ViewState["ddSelectedValue"]).ToString();
}
}

Related

DropDownLists Issue ASP.NET

I really have a serious issues with postback, I have 3 dropdownlists, the first one contain data from a database, it's the countries, the second is the same but for the cities who depends the selected value on the first dropdownlist which is the countries, and the third dropdownlist is the airlines who depends on the selected value of the second dropdownlist which is the cities.
So the first two dropdownlists work perfectly, but the third dropdownlist will never work even with autopostback true and false, it will always refresh on to the first value and I wrote if(!IsPostback) so I really I'm frustrated about this issue.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Configuration;
using System.Data;
using System.IO;
namespace Hijazi_Airlines
{
public partial class Book : System.Web.UI.Page
{
SqlConnection sqlcon = new SqlConnection(ConfigurationManager.ConnectionStrings["HAirlines"].ConnectionString);
protected void Page_Init(object sender, EventArgs e)
{
if (Session["Username"] != null)
{
Sign.Text = "Sign Out";
}
else
{
}
gather_countries();
gather_cities();
gather_Tocountries();
gather_Tocities();
}
private void gather_date()
{
try
{
string query = "SELECT Depart FROM Flights where Airlines_id=" + Airlin.SelectedValue;
SqlCommand sqlcmd = new SqlCommand(query, sqlcon);
sqlcon.Open();
SqlDataReader reader = sqlcmd.ExecuteReader();
reader.Read();
Response.Write(reader[0].ToString());
sqlcon.Close();
}
catch
{
}
sqlcon.Close();
}
private void gather_cities()
{
FromCit.Items.Clear();
string cities = "select * from Cities where country_id = " + FromCount.SelectedValue;
CountriesAndCities(cities, FromCit);
}
private void gather_Tocities()
{
ToCit.Items.Clear();
string cities = "select * from Cities where country_id = " + To.SelectedValue;
CountriesAndCities(cities, ToCit);
}
private void gather_countries()
{
string Countries = "select * from Countries order by country desc";
CountriesAndCities(Countries, FromCount);
}
private void gather_Tocountries()
{
string Countries = "select * from Countries order by country desc";
CountriesAndCities(Countries, To);
}
private void CountriesAndCities(string query, DropDownList dp)
{
SqlCommand sqlcmdC = new SqlCommand(query, sqlcon);
sqlcon.Open();
SqlDataReader reader = sqlcmdC.ExecuteReader();
while (reader.Read())
{
ListItem item = new ListItem();
item.Text = reader[1].ToString();
item.Value = reader[0].ToString();
dp.Items.Insert(0, item);
}
sqlcon.Close();
}
protected void Hom_Click(object sender, EventArgs e)
{
Response.Redirect("Home.aspx");
}
protected void SignIN_Click1(object sender, EventArgs e)
{
if (Sign.Text == "Sign Out")
{
Session.RemoveAll();
Session.Abandon();
Sign.Text = "Sign In";
}
else
{
Response.Redirect("Login.aspx");
}
}
protected void Contact_Click(object sender, EventArgs e)
{
Response.Redirect("Contact.aspx");
}
protected void FromCount_SelectedIndexChanged(object sender, EventArgs e)
{
gather_cities();
}
protected void To_SelectedIndexChanged(object sender, EventArgs e)
{
gather_Tocities();
}
protected void Airlin_SelectedIndexChanged(object sender, EventArgs e)
{
gather_date();
}
}
}
Problem is here:
string query = "SELECT Depart FROM Flights where Airlines_id=" + Airlin.SelectedValue;
You said that the third dropdownlist is the airlines who depends on the selected value of the second dropdownlist which is the cities. But in the above code you are selecting the value of third dropdown which makes no sense as it doesn't have any value.
So instead of above code, change the id value to this:
string query = "SELECT Depart FROM Flights where Airlines_id=" + YourCityDropDownId.SelectedValue;
Check this and let me know.
Your problem is permanently recreate ddl.
gather_Tocountries();
gather_Tocities();
Well, for solution this problem, you need after created your ddls set selected value for ToCit and To ddl.
ToCit.SelectedValue = yourValue; //Something like this;
But code which you wrote is not productive, because you each time call database
if you wanna init your ddl after select in prev, just call your method
CountriesAndCities in SelectedIndexChanged. First init you can do in pageInit or pageLoad but with use if(isPostBack){your first ddl init}
for example
PageLoad(){
if(IsPostBack){
string Countries = "select * from Countries order by country desc";
CountriesAndCities(Countries, FromCount);
}
}
For other ddl the same
then
protected void FromCount_SelectedIndexChanged(object sender, EventArgs e)
{
gather_cities();
}

How to display the correct amount of records for a chart in visual studios c#

Hello all just an update, I am still facing the issues of getting the chart to display the correct number of records. I have discovered where the chart is currently getting it's numbers from however it makes no sense as to why it is using those numbers. It is from a column in the database called "mpm_code" however I have never specified for the chart to use those numbers. Here are the numbers in the database:
Here is the chart
And here is my code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.OleDb;
namespace RRAS
{
public partial class formRRAS : Form
{
public OleDbConnection DataConnection = new OleDbConnection();
string cmbRFR_item;
public formRRAS()
{
InitializeComponent();
}
//When the form loads it sets the intial combo box RFR item to null
private void formRRAS_Load(object sender, EventArgs e)
{
// TODO: This line of code loads data into the 'database1DataSet.tblReject_test' table. You can move, or remove it, as needed.
this.tblReject_testTableAdapter.Fill(this.database1DataSet.tblReject_test);
cmbRFR.SelectedItem = "";
this.AcceptButton = btnSearch;
}
//AddRFR method, called in the NewRFRPopup
public void AddRFR(object item)
{
cmbRFR.Items.Add(item);
}
private void change_cmbSubRFR_items()
{
cmbSubRFR.Items.Clear();//Clear all items in cmbSubRFR comboBox.
switch (cmbRFR_item)//Adding your new items to cmbSubRFR.
{
case "":
cmbSubRFR.Items.Add("");
cmbSubRFR.Text = "";
break;
case "POSITIONING":
cmbSubRFR.Items.Add("");
cmbSubRFR.Items.Add("Anatomy cut-off");
cmbSubRFR.Items.Add("Rotation");
cmbSubRFR.Items.Add("Obstructed view");
cmbSubRFR.Items.Add("Tube or grid centering");
cmbSubRFR.Items.Add("Motion");
cmbSubRFR.Text = "";
break;
case "ARTEFACT":
cmbSubRFR.Items.Add("");
cmbSubRFR.Items.Add("ARTEFACT");
cmbSubRFR.Text = "ARTEFACT";
cmbSubRFR.Text = "";
break;
case "PATIENT ID":
cmbSubRFR.Items.Add("");
cmbSubRFR.Items.Add("Incorrect Patient");
cmbSubRFR.Items.Add("Incorrect Study/Side");
cmbSubRFR.Items.Add("User Defined Error");
cmbSubRFR.Text = "";
break;
case "EXPOSURE ERROR":
cmbSubRFR.Items.Add("");
cmbSubRFR.Items.Add("Under Exposure");
cmbSubRFR.Items.Add("Over Exposure");
cmbSubRFR.Items.Add("Exposure Malfunction");
cmbSubRFR.Text = "";
break;
case "TEST IMAGES":
cmbSubRFR.Items.Add("");
cmbSubRFR.Items.Add("Quality Control");
cmbSubRFR.Items.Add("Service/Test");
cmbSubRFR.Text = "";
break;
}
}
private void cmbRFR_SelectedIndexChanged(object sender, EventArgs e)
{
if (cmbRFR_item != cmbRFR.SelectedItem.ToString())//This controls the changes in cmbRFR about selected item and call change_cmbSubRFR_items()
{
cmbRFR_item = cmbRFR.SelectedItem.ToString();
change_cmbSubRFR_items();
}
}
//The code for the button that closes the application
private void btnSearch_Click(object sender, EventArgs e)
{
//This creates the String Publisher which grabs the information from the combo box on the form.
//Select and Dataconnection are also defined here.
string Department = String.IsNullOrEmpty(txtDepartment.Text) ? "%" : txtDepartment.Text;
string Start_Date = String.IsNullOrEmpty(txtStart.Text) ? "%" : txtStart.Text;
string End_Date = String.IsNullOrEmpty(txtEnd.Text) ? "%" : txtEnd.Text;
string Anatomy = String.IsNullOrEmpty(txtAnatomy.Text) ? "%" : txtAnatomy.Text;
string RFR = String.IsNullOrEmpty(cmbRFR.Text) ? "%" : cmbRFR.Text;
string Comment = String.IsNullOrEmpty(cmbSubRFR.Text) ? "%" : cmbSubRFR.Text;
string Select = "SELECT * FROM tblReject_test WHERE department_id LIKE '" + Department + "'" + "AND body_part_examined LIKE'" + Anatomy + "'" + "AND study_date LIKE'" + Start_Date + "'" + "AND study_date LIKE'" + End_Date + "'" + "AND reject_category LIKE'" + RFR + "'" + "AND reject_comment LIKE'" + Comment + "'";
//DataConnection connects to the database.
string connectiontring = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=|DataDirectory|\\Database1.mdb";
DataConnection = new OleDbConnection(connectiontring);
//The DataAdapter is the code that ensures both the data in the Select and DataConnection strings match.
OleDbDataAdapter rdDataAdapter = new OleDbDataAdapter(Select, DataConnection);
try
{
//It then clears the datagridview and loads the data that has been selected from the DataAdapter.
database1DataSet.tblReject_test.Clear();
rdDataAdapter.Fill(this.database1DataSet.tblReject_test);
}
catch (OleDbException exc)
{
System.Windows.Forms.MessageBox.Show(exc.Message);
}
} //End of Search button
//Temporary button thats loads the chart when clicked
private void btnLoadChart_Click(object sender, EventArgs e)
{
charRejections.Series["RFR"].Points.Clear();
{
string connectiontring = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=|DataDirectory|\\Database1.mdb";
DataConnection = new OleDbConnection(connectiontring);
try
{
int count = database1DataSet.Tables["tblReject_test"].Rows.Count;
DataConnection.Open();
OleDbCommand command = new OleDbCommand();
command.Connection = DataConnection;
string query = "SELECT COUNT(*) as count, reject_category FROM tblReject_test GROUP BY reject_category";
command.CommandText = query;
OleDbDataReader reader = command.ExecuteReader();
while (reader.Read())
{
charRejections.Series["RFR"].Points.AddXY(reader["reject_category"].ToString(), reader[count]);
}
DataConnection.Close();
}
catch (Exception ex)
{
MessageBox.Show("Error " + ex);
}
}
} //end of load chart button
//These buttons are all from the file menu bar
//A simple button that closes the application
private void exitToolStripMenuItem_Click(object sender, EventArgs e)
{
this.Close();
}
//This button loads the NewRFRPopup form
private void addRFRToolStripMenuItem_Click(object sender, EventArgs e)
{
NewRFRPopup popup = new NewRFRPopup(this);
popup.ShowDialog();
}
private void printChartToolStripMenuItem_Click(object sender, EventArgs e)
{
charRejections.Printing.PrintDocument.DefaultPageSettings.Landscape = true;
charRejections.Printing.PrintPreview();
}
//End of file menu bar
//These buttons change the format of the chart
private void btnPie_Click(object sender, EventArgs e)
{
this.charRejections.Series["RFR"].ChartType = System.Windows.Forms.DataVisualization.Charting.SeriesChartType.Pie;
}
private void btnBar_Click(object sender, EventArgs e)
{
this.charRejections.Series["RFR"].ChartType = System.Windows.Forms.DataVisualization.Charting.SeriesChartType.Column;
}
private void btnSideways_Click(object sender, EventArgs e)
{
this.charRejections.Series["RFR"].ChartType = System.Windows.Forms.DataVisualization.Charting.SeriesChartType.Bar;
}
private void btnLine_Click(object sender, EventArgs e)
{
this.charRejections.Series["RFR"].ChartType = System.Windows.Forms.DataVisualization.Charting.SeriesChartType.Line;
}
//end of chart formatting
}
}
The Issue has been sorted thanks to a friend of mine. This relates to the code that TaW posted the other day. Thanks for everyone's time and suggestions. The fixed code is below:
private void btnLoadChart_Click(object sender, EventArgs e)
{
charRejections.Series["RFR"].Points.Clear();
{
string connectiontring = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=|DataDirectory|\\Database1.mdb";
DataConnection = new OleDbConnection(connectiontring);
try
{
DataConnection.Open();
OleDbCommand command = new OleDbCommand();
command.Connection = DataConnection;
string query = "SELECT COUNT(reject_category) as reject, reject_category FROM tblReject_test GROUP BY reject_category";
command.CommandText = query;
OleDbDataReader reader = command.ExecuteReader();
while (reader.Read())
{
charRejections.Series["RFR"].Points.AddXY(reader["reject_category"].ToString(), reader["reject"].ToString());
}
DataConnection.Close();
}
catch (Exception ex)
{
MessageBox.Show("Error " + ex);
}
}
}//end of load chart button

Session name is not retrieved in master page

i using a single master page in asp.net for log-In and Log-Out functionality...
but in master page session name takes null value.
Here is my code ,please help me...
MasterPage.master.cs
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
if (Session["name"] == null)
{
Panel2.Visible = false;
Panel1.Visible = true;
}
else if (Session["name"] != null)
{
Panel1.Visible = false;
Panel2.Visible = true;
Label2.Text = "WELCOME | Mr." + Session["name"].ToString();
}
}
}
protected void LoginStatus1_LoggedOut(object sender, EventArgs e)
{
Session.Clear();
Session.Abandon();
}
my homepage.aspx.cs
protected void Button1_Click(object sender, EventArgs e)
{
string st="select Label4,Label3 FROM Register1_master WHERE Label4='" + TextBox1.Text + "' and Label3='" + TextBox2.Text + "'";
cmd = new SqlCommand(st, sqlcon);
cmd.Connection.Open();
string result= null;
Object value=cmd.ExecuteScalar ();
if ( value != null)
{
result = value.ToString ();
Session["name"] = TextBox1.Text;
Response.Redirect("Main.aspx");
}
else
{
Label3.Text="Invalid username or password";
}
cmd.Connection.Close();
}
after the login from homepage i'll be go on Main.aspx page
my Main.aspx.cs
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
HyperLink link = (HyperLink)Master.FindControl("HyperLink1");
link.Visible = false;
HyperLink link1 = (HyperLink)Master.FindControl("HyperLink2");
link1.Visible = true;
Label masterlbl = (Label)Master.FindControl("Label2");
string login = Convert.ToString(Session["name"]);
Session["name"] = login;
}
}
Have you try like this :
int result= null;
result= = Convert.ToInt32(cmd.ExecuteScalar());
Use the ExecuteScalar method to retrieve a single value (for example, an aggregate value) from a database. This requires less code than using the ExecuteReader method, and then performing the operations that you need to generate the single value using the data returned by a SqlDataReader.
A typical ExecuteScalar query can be formatted as in the following C# example:
cmd.CommandText = "SELECT COUNT(*) FROM dbo.region";
Int32 count = (Int32) cmd.ExecuteScalar();
Please refer MSDN

save username but shows name in c#

I'm working with c#, in vs 2008, framework 3.5, I need to save the username and when
the user log in, it shows he/her first and last name, at this point can save it, and
that is what I want but need to show to the user not his/her username just the first and
last name. here is my code, thanks in advance.
//code in the login
ClPersona login = new ClPersona();
bool isAuthenticated = login.sqlLogin1((txtUsuario.Text), (txtPassword.Text));
if (isAuthenticated)
{
Session["sesionicontrol"] = login.NombreUsuario;
Response.Redirect("../MENU/menu1.aspx");
}
//code in the form where shows the username but I want the first and last name
public partial class menu2 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
lblNombreUsuario.Text = (string)Session["sesionicontrol"];
if (!IsPostBack)
//ClPersona class
public Boolean sqlLogin1(string nombreUsuario, string password)
{
string stSql = "select * from usuarios where usuario='" + nombreUsuario + "' and
pass='" + password + "'and id_rol='1'";
Bd miBd = new Bd();
DataTable dt = miBd.sqlSelect(stSql);
DataSet ds = new DataSet();
ds.Tables.Add(dt);
//return ds;
if (dt.Rows.Count > 0)
{
return true;
}
else
{
return false;
}
}
Modify two sections
First
if (isAuthenticated)
{
Session["YouObject"] = login;//<--
Session["sesionicontrol"] = login.NombreUsuario;
Response.Redirect("../MENU/menu1.aspx");
}
Second
protected void Page_Load(object sender, EventArgs e)
{
if(Session["YouObject"] != null)
{
ClPersona obj = (ClPersona )Session["YouObject"];
lblNombreUsuario.Text = string.Format("{0}-{1}", obj.FirstName, obj.LastName )
}
lblNombreUsuario.Text = (string)Session["sesionicontrol"];
....
}

FileUpload in FormView

I have a problem regarding with add an image URL within a database.I'm using fileupload method within formview in ASP.Net.And I have a table called duyurular
which can be record a image URL.BTW,I'm using SQL Server Database.
My question is;I'm doing the process update,delete and to make an announcement in the FormView.I can upload those images within folder called "img" with FileUpload.
However,I want to record it within database as well.when to add within database another those infos,there are no the image URL.
Finally,I can't add the image URL within database.
Here is my code;
public partial class panel_yoneticipaneli : System.Web.UI.Page
{
FileUpload dosya, dosya1;
//TextBox t1, t2, t3;
//Button btn;
SqlConnection con;
static string str = "Data Source=SERT;Initial Catalog=Mmakina;Integrated Security=True";
string yol = "";
protected void Page_Load(object sender, EventArgs e)
{
dosya = (FileUpload)FormView2.FindControl("FileUpload1");
dosya1 = (FileUpload)FormView2.FindControl("FileUpload2");
// btn = (Button)FormView2.FindControl("ResimKaydetButonu");
//t1 = (TextBox)FormView2.FindControl("DuyuruBaslikTextBox");
//t2 = (TextBox)FormView2.FindControl("DuyuruIcerikTextBox");
//t3 = (TextBox)FormView2.FindControl("DuyuruTarihiTextBox");
Label1.Visible = false;
if (Session["KullaniciID"]!=null)
{
con = new SqlConnection(str);
SqlCommand sorgu = new SqlCommand("SELECT * FROM Kullanici WHERE KullaniciAdi=#KullaniciAdi", con);
sorgu.Parameters.Add("#KullaniciAdi", SqlDbType.VarChar).Value = Session["KullaniciAdi"];
con.Open();
SqlDataReader oku = sorgu.ExecuteReader(CommandBehavior.CloseConnection);
Label1.Visible = true;
while (oku.Read())
{
Label1.Text = oku["KullaniciAdi"].ToString();
}
}
else {
Response.Redirect("error.aspx");
}
}
protected void Button1_Click(object sender, EventArgs e)
{
FormsAuthentication.SignOut();
Roles.DeleteCookie();
Session.Clear();
Response.Redirect("giris.aspx");
}
protected void btn_Click(object sender,EventArgs e) {
try
{
if (dosya.HasFile)
{
dosya.SaveAs(Server.MapPath("~/img/") + dosya.FileName);
System.Drawing.Image resim = System.Drawing.Image.FromFile(Server.MapPath("~/img/") + dosya.FileName);
yol = "img/" + dosya.FileName;
resim.Dispose();
DbUpload();
}
}
catch (Exception ex)
{
}
}
public void DbUpload() {
try {
SqlConnection sc = new SqlConnection("Data Source=SERT;Initial Catalog=Mmakina;Integrated Security=True");
SqlCommand scom = new SqlCommand("insert into Duyuru(DuyuruResmi) values(#DuyuruResmi)", sc);
scom.Parameters.AddWithValue("#DuyuruResmi", dosya.FileName);
scom.ExecuteNonQuery();
sc.Close();
}catch(Exception p){
p.Message.ToString();
}
}
protected void UpdateButton_Click(object sender, EventArgs e)
{
try
{
if (dosya.HasFile)
{
dosya.SaveAs(Server.MapPath("~/img/") + dosya.FileName);
yol = "img/" + dosya.FileName;
Response.Write("Fileupload çalışıyor...");
DbUpload();
}
}
catch (Exception ex)
{
}
}
thanks in advance for all comments you can share.
I suggest that you just upload the image name without specifying the full URL, and you can save the image base path in the web.config like '<add key="ImagesBasePath" value="/img" />' so you can change the path were you have your images and you can control the view of this image by concatenating the Image name to ConfigurationManager.AppSettings["ImagesBasePath"] so this will be better.
You have to use Formview ItemInserting Event, where you can pass in the built URL.
protected void frmAsset_ItemInserting(object sender, FormViewInsertEventArgs e)
{
if (dosya.HasFile)
{
dosya.SaveAs(Server.MapPath("~/img/") + dosya.FileName);
e.NewValues["URL"] = "img/" + dosya.FileName;
}
}

Categories