How to Put two DataValueFields? - c#

How do I bind a product name, then get a product id and price in the label result? The three attributes are from the same table in DB.
Code:
public partial class CreateOrder : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (Page.IsPostBack == false) bindListBox();
}
}
private void bindListBox()
{
ddlProduct.DataSource = getReader();
ddlProduct.DataTextField = "productName";
ddlProduct.DataValueField = "IDANDPRICE";
ddlProduct.DataBind();
}
private SqlDataReader getReader()
{
//get connection string from web.config
string strConnectionString =
ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
SqlConnection myConnect = new SqlConnection(strConnectionString);
string strCommandText = "SELECT productName, productID,productPrice,(productID + '-' + productPrice) AS IDANDPRICE from Product";
SqlCommand cmd = new SqlCommand(strCommandText, myConnect);
myConnect.Open();
SqlDataReader reader = cmd.ExecuteReader(CommandBehavior.CloseConnection);
return reader;
}
protected void DropDownList2_SelectedIndexChanged(object sender, EventArgs e)
{
Label1.Text = "";
Label1.Text += "productName:" + ddlProduct.SelectedItem.Text + "<br/>";
Label2.Text = "";
Label2.Text += "IDANDPRICE:" + ddlProduct.SelectedItem.ToString() ;
}

I find the following errors:
1- cast number filed to nvarchar in sql query
2- set AutoPostBack property of listbox to true
3- use ddlProduct.SelectedItem.Value for label2
I create a page and use your code and apply above suggestion, the following code work perfectly.
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (Page.IsPostBack == false) bindListBox();
}
private void bindListBox()
{
ddlProduct.DataSource = getReader();
ddlProduct.DataTextField = "name";
ddlProduct.DataValueField = "IdAndName";
ddlProduct.DataBind();
}
private SqlDataReader getReader()
{
//get connection string from web.config
string strConnectionString = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
SqlConnection myConnect = new SqlConnection(strConnectionString);
string strCommandText = "SELECT Id,Name,CAST( id as nvarchar(10) )+'-'+Name as IdAndName FROM Product";
SqlCommand cmd = new SqlCommand(strCommandText, myConnect);
myConnect.Open();
SqlDataReader reader = cmd.ExecuteReader(CommandBehavior.CloseConnection);
return reader;
}
protected void DropDownList2_SelectedIndexChanged(object sender, EventArgs e)
{
Label1.Text = "";
Label1.Text += "productName:" + ddlProduct.SelectedItem.Text + "<br/>";
Label2.Text = "";
Label2.Text += "IDANDPRICE:" + ddlProduct.SelectedItem.Value;
}
}

Related

How to add textbox data to a database?

I am making a school project and i need to put text input (name and gender) into a database. This database (the names and genders) then have to be shown in a listbox. The code i have at the moment is put below, how can i make it work? Thanks in advance!
private void Form1_Load(object sender, EventArgs e)
{
using (connection = new SqlConnection(connectionString))
using (SqlDataAdapter adapter = new SqlDataAdapter("SELECT * FROM
Persoon", connection))
{
connection.Open();
DataTable PersoonTable = new DataTable();
adapter.Fill(PersoonTable);
lb_gebruikers.DisplayMember = "Naam";
lb_gebruikers.ValueMember = "Id";
lb_gebruikers.DataSource = PersoonTable;
}
}
private void button1_Click(object sender, EventArgs e)
{
string naam = tb_naam.Text;
string geslacht = tb_geslacht.Text;
Persoon nieuwpersoon = new Persoon(naam, geslacht);
personen.Add(nieuwpersoon);
foreach (var Persoon in personen)
{
lb_gebruikers.Items.Add("Naam: " + nieuwpersoon.Naam +
"Geslacht: " + nieuwpersoon.Geslacht);
}
}
As i understand you just have to add a insert between button1.click and addToList process.
private void btnSave_Click(object sender, EventArgs e)
{
try
{
SqlConnection con = new SqlConnection("Server =.;Database=People; Integrated Security = true");
con.Open();
SqlCommand cmd = new SqlCommand(); // you can define commandText and connection in SqlCommand(defineArea);
cmd.Connection = con; // like; cmd = newSqlCommand("Insert into...",con);
string name = txtName.Text;
string gender = txtGender.Text;
cmd.CommandText = "Insert into Person(Name,Gender)values('" + name + "','" + gender + "')";
cmd.ExecuteNonQuery();
cmd.Dispose();
con.Close();
lstBxPerson.Items.Add(name + " - " + gender);
MessageBox.Show("Save Success!");
}
catch (Exception ex)
{
MessageBox.Show("Exception : "+ex);
}
}
Database Name : People
Table Name : Person
All Parts Image :

The name 'GetData(cmd)' does not exist in the current context

I have this error "The name 'GetData' does not exist in the current context". I had tried to declare the getdata() function but it still got error.
public partial class v2_kradescription : System.Web.UI.Page
{
private String conn = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
my c# code behind already has
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
{
BindData();
}
}
here, I'm using getdata()
protected void BindData()
{
string conn = "select kr_id,kr_position,kr_description from tblKRAObjective";
SqlCommand cmd = new SqlCommand(conn);
GridView1.DataSource = GetData(cmd);
GridView1.DataBind();
}
protected void AddNewJob(object sender, EventArgs e)
{
if (e.Equals("btnAdd"))
{
string jid = ((TextBox)GridView1.FooterRow.FindControl("txtid")).Text;
string jposition = ((TextBox)GridView1.FooterRow.FindControl("txtposition")).Text;
string jdescription = ((TextBox)GridView1.FooterRow.FindControl("txtdescription")).Text;
SqlConnection con = new SqlConnection(conn);
SqlCommand cmd = new SqlCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "insert into tblJobDescription (j_id, j_position, j_description) " + "values(#j_id, #j_position, #j_description);" + "select j_id,j_position,j_description from tblJobDescription";
cmd.Parameters.Add("#j_id", SqlDbType.VarChar).Value = jid;
cmd.Parameters.Add("#j_position", SqlDbType.VarChar).Value = jposition;
cmd.Parameters.Add("#j_description", SqlDbType.VarChar).Value = jdescription;
GridView1.DataSourceID = GetData(con);
GridView1.DataBind();
}
}
protected void EditDescription(object sender, GridViewEditEventArgs e)
{
GridView1.EditIndex = e.NewEditIndex;
BindData();
}
protected void CancelEdit(object sender, GridViewCancelEditEventArgs e)
{
GridView1.EditIndex = -1;
BindData();
}
protected void UpdateDescription(object sender, GridViewUpdateEventArgs e)
{
string jid = ((TextBox)GridView1.FooterRow.FindControl("txtkr_id")).Text;
string jposition = ((TextBox)GridView1.FooterRow.FindControl("txtkr_position")).Text;
string jdescription = ((TextBox)GridView1.FooterRow.FindControl("txtkr_description")).Text;
SqlCommand con = new SqlCommand(conn);
SqlCommand cmd = new SqlCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "update tblJobDescription set j_id=#j_id,j_position=#j_position where j_id=#j_id ";
cmd.Parameters.Add("#j_id", SqlDbType.Int).Value = jid;
cmd.Parameters.Add("#j_position", SqlDbType.Int).Value = jposition;
cmd.Parameters.Add("#j_description", SqlDbType.Int).Value = jdescription;
GridView1.EditIndex = -1;
GridView1.DataSourceID = GetData(cmd);
GridView1.DataBind();
}
protected void DeleteDescription(object sender, EventArgs e)
{
LinkButton lnkRemove = (LinkButton)sender;
SqlConnection con = new SqlConnection(conn);
SqlCommand cmd = new SqlCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = " delete from tblJobDescription where j_id=#j_id";
cmd.Parameters.Add("#j_id", SqlDbType.VarChar).Value = lnkRemove.CommandArgument;
GridView1.DataSource = GetData(cmd);
GridView1.DataBind();
}
protected void OnPaging(object sender, GridViewPageEventArgs e)
{
BindData();
GridView1.PageIndex = e.NewPageIndex;
GridView1.DataBind();
}
protected void btnPreview_Click(object sender, EventArgs e)
{
Response.Redirect("kra_pdf.aspx");
}
protected void btnSubmit_Click(object sender, EventArgs e)
{
if (Page.IsValid)
{
string jicno = (string)(Session["s_icno"]);
string jobid = "";
string jobdescription = "";
string jobposition = "";
try
{
string query = "InsertJobDescription";
// get requester name, companyid, primary appraiser of requester
String queryA = "SELECT kr_id, kr_description, kr_position FROM tblKRAObjective WHERE s_icno = '" + jicno + "' ";
SqlCommand cmdA = new SqlCommand(conn);
SqlDataReader drA = cmdA.ExecuteReader();
if (drA.Read())
{
jobid = drA["j_id"].ToString();
jicno = drA["j_icno"].ToString();
jobdescription = drA["j_descpription"].ToString();
jobposition = drA["j_position"].ToString();
}
drA.Close();
SqlCommand cmd1 = new SqlCommand(conn);
cmd1.CommandType = CommandType.StoredProcedure;
cmd1.Parameters.Add("#j_icno", SqlDbType.NVarChar).Value = jicno.ToString();
cmd1.Parameters.Add("#j_description", SqlDbType.NVarChar).Value = jobdescription.ToString();
cmd1.Parameters.Add("#j_position", SqlDbType.NVarChar).Value = jobposition.ToString();
cmd1.ExecuteNonQuery();
}
catch (Exception ex)
{
lblMsg.Text = ex.Message; //" Error while saving the record.";
}
Response.Redirect("kra_dashboard.aspx");
}
}
but anyway, I'm getting the error
The name 'GetData' does not exist in the current context
so, where is my mistake ?

How to update data in grid view?

I try to update data in grid view. When i press edit button in grid view row data will be fill in other page in relevant control and press update button data will be update.
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "EditButton")
{
int index = Convert.ToInt32(e.CommandArgument);
GridViewRow row = GridView1.Rows[index];
Response.Redirect("~/Home.aspx?Id=" + row.Cells[0].Text);
}
}
Destination page code
public partial class Home : System.Web.UI.Page
{
Property p = new Property();
int Id = 0;
protected void Page_Load(object sender, EventArgs e)
{
Id = Convert.ToInt32(Request.QueryString["Id"].ToString());
if (!IsPostBack)
{
BindTextBoxvalues();
}
}
private void BindTextBoxvalues()
{
string constr = ConfigurationManager.ConnectionStrings["conn"].ConnectionString;
SqlConnection con = new SqlConnection(constr);
SqlCommand cmd = new SqlCommand("select * from tblUsers where Id=" + Id, con);
DataTable dt = new DataTable();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);
txtUsername.Text = dt.Rows[0][0].ToString();
txtEmail.Text = dt.Rows[0][1].ToString();
txtDob.Text = dt.Rows[0][2].ToString();
txtPass.Text = dt.Rows[0][3].ToString();
}
protected void btnUpdate_Click(object sender, EventArgs e)
{
string constr = ConfigurationManager.ConnectionStrings["conn"].ConnectionString;
SqlConnection con = new SqlConnection(constr);
SqlCommand cmd = new SqlCommand("update tblUsers set UserName='" + txtUsername .Text + "',Email='" + txtEmail.Text + "',DOB=" + txtDob.Text + ",Password='" + txtPass.Text + "' where Id=" + Id, con);
con.Open();
int result = cmd.ExecuteNonQuery();
con.Close();
if (result == 1)
{
ScriptManager.RegisterStartupScript(this, this.GetType(), "ShowSuccess", "javascript:alert('Record Updated Successfully');", true);
}
Response.Redirect("~/Admin/Home.aspx");
}
}
Error: Input string was not in a correct format.
protected void Page_Load(object sender, EventArgs e)
{
Id = Convert.ToInt32(Request.QueryString["Id"].ToString());
if (!IsPostBack)
{

How to show the selected value from the drop down list and show it in gridview

I want it to show the selected value from the drop down list and show it on gridview. It is supposed to query from the database using Where to indicate the selected value to show. For example, I select james from the drop down list. It supposes to go to the database and query james row. After that the grid view is supposed to show only one value which james. But now I am having a problem where the grid view show every data that is available in the database.
public partial class Search_Engine : System.Web.UI.Page
{
#region Database
static string HostName = "localhost";
static string DatabaseName = "finalproject";
static string TableName = "truckinfo";
//static string TableBucket = "bucketbrigade";
static string UserName = "root";
static string Password = "";
//--- Used for access to database infomation-----
string ConnStr = "Data Source=" + HostName + ";" +
"Database=" + DatabaseName + ";" +
"User ID=" + UserName + ";" +
"Password=" + Password;
string Qry = "";
MySqlConnection Con;
MySqlCommand Cmd;
MySqlDataReader Rdr;
#endregion
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindData();
using (Con = new MySqlConnection(ConnStr))
{
Con.Open();
using (Cmd = new MySqlCommand("SELECT * FROM truckinfo", Con))
{
using (Rdr = Cmd.ExecuteReader())
{
if (Rdr.HasRows)
{
DropDownList1.DataSource = Rdr;
DropDownList1.DataValueField = "truckplateno";
DropDownList1.DataTextField = "truckplateno";
DropDownList1.DataBind();
}
}
}
}
}
}
private void BindData()
{
DataTable dt = new DataTable();
try
{
MySqlConnection Con = new MySqlConnection(ConnStr);
Con.Open();
MySqlDataAdapter da = new MySqlDataAdapter("SELECT * FROM " +
DatabaseName + "." + TableName , Con);
da.Fill(dt);
if (dt.Rows.Count > 0)
{
GridView1.DataSource = dt;
GridView1.DataBind();
}
Con.Close();
}
catch (Exception ex)
{
Response.Write(ex.ToString());
}
}
protected void TextBox1_TextChanged(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
}
protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
{
}
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
Con = new MySqlConnection(ConnStr);
Con.Open();
try
{
String getquery;
// String a;
getquery = DropDownList1.Text;
TextBox1.Text = getquery;
// a = TextBox2.Text;
// TextBox1.Text = a;
Qry = #"SELECT * FROM finalproject.truckinfo WHERE truckplateno=" + "'" + getquery + "'" + ";";
Cmd = new MySqlCommand(Qry, Con);
Cmd.ExecuteNonQuery();
Con.Close();
BindData();
}
catch (Exception ex)
{
Response.Write(ex.ToString());
}
}
}
You need to get the selected value using SelectedValue of dropdownlist and then query database using this value.
getquery = DropDownList1.SelectedValue;
Also you are using BindData method which will always select all data from database you need to seprate this method so only selected data is bind to gridview.
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
String getquery;
getquery = DropDownList1.Text;
MySqlConnection Con = new MySqlConnection(ConnStr);
Con.Open();
MySqlDataAdapter da = new MySqlDataAdapter("SELECT * FROM finalproject.truckinfo WHERE truckplateno='" + getquery + "'", Con);
da.Fill(dt);
if (dt.Rows.Count > 0)
{
GridView1.DataSource = dt;
GridView1.DataBind();
}
Con.Close();
}
You are calling ExecuteNonQuey function which is used to Insert or Update data in database so it will not return any data.
Also when using SqlDataAdapter you don't need to explicitly call
Open and Close function for opening and closing connection.
Change your DropDownlist_SelectedIndexChanged function to the following:
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
Con = new MySqlConnection(ConnStr);
DataTable dt = new DataTable();
try
{
Con.Open();
string getquery = DropDownList1.SelectedValue;
TextBox1.Text = getquery;
// a = TextBox2.Text;
// TextBox1.Text = a;
Qry = #"SELECT * FROM finalproject.truckinfo WHERE truckplateno=" + "'" + getquery + "'" + ";";
MySqlCommand ddlCMD = new MySqlCommand(Qry, Con);
MySqlDataAdapter msda = new MySqlDataAdapter(ddlCMD);
msda.Fill(dt);
GridView1.DataSource = dt;
GridView1.DataBind();
}
catch (Exception ex)
{
Response.Write(ex.ToString());
}
finally{
Con.Close();
}
}

updated values are not getting stored in the textbox

protected void Page_Load(object sender, EventArgs e)
{
cnst = "Data Source=IBM369-R9WAKY5;Initial Catalog=anudatabase;Integrated Security=True";
cn = new SqlConnection(cnst);
cn.Open();
st = "select * from patient_db where unique_id = 123";
cmd = new SqlCommand(st, cn);
dr = cmd.ExecuteReader();
if (dr.Read())
{
Label9.Text = dr.GetString(1);
Label10.Text = dr.GetInt16(2).ToString();
Label11.Text = dr.GetString(6);
Label12.Text = dr.GetString(7);
TextBox1.Text = dr.GetString(3);
TextBox2.Text = dr.GetDecimal(4).ToString();
}
cn.Close();
}
//Button click function
protected void Button1_Click(object sender, EventArgs e)
{
cn.Open();
st = "update patient_db set address ='" + TextBox1.Text + "' ,phone=" + TextBox2.Text+"where unique_id=123";
cmd = new SqlCommand(st, cn);
int result2 = cmd.ExecuteNonQuery();
if (Convert.ToBoolean(result2))
{
result1.Text = "details updated successfully";
}
cn.Close();
}
After assigning the value to textbox from the database,if I type some other new value in the text box,it is not taking the new value,it still persists with the old value.May i know the reason and solution for this? thanks in advance
Write a method LoadData, move the code from page_load into this method. Then call this method from page_load wrapped in a if(!IsPostBack)-check. Call this method also from the button-click event handler after you've updated the values.
private void LoadData()
{
using (var cn = new SqlConnection("Data Source=IBM369-R9WAKY5;Initial Catalog=anudatabase;Integrated Security=True"))
{
cn.Open();
using(var cmd = new SqlCommand("select * from patient_db where unique_id = 123", cn))
using (var dr = cmd.ExecuteReader())
{
if (dr.Read())
{
Label9.Text = dr.GetString(1);
Label10.Text = dr.GetInt16(2).ToString();
Label11.Text = dr.GetString(6);
Label12.Text = dr.GetString(7);
TextBox1.Text = dr.GetString(3);
TextBox2.Text = dr.GetDecimal(4).ToString();
}
}
}
}
protected void Page_Load(object sender, EventArgs e)
{
if(!Page.IsPostBack)
{
LoadData();
}
}
protected void Button1_Click(object sender, EventArgs e)
{
// ... update
LoadData();
}
Important notes:
Also use the using-statement for every object implementing IDisposable like the connection or the datareader. On that way all unmanaged resources are disposed properly. Even in case of an error.
If 123 is just an example and actually is a value provided by the user use sql-parameters to prevent sql-injection. No, use them always.
Add IsPostBack control at Page_Load method. Because before Button_Click event Page_Load event firing.
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
{
cnst = "Data Source=IBM369-R9WAKY5;Initial Catalog=anudatabase;Integrated Security=True";
cn = new SqlConnection(cnst);
cn.Open();
st = "select * from patient_db where unique_id = 123";
cmd = new SqlCommand(st, cn);
dr = cmd.ExecuteReader();
if (dr.Read())
{
Label9.Text = dr.GetString(1);
Label10.Text = dr.GetInt16(2).ToString();
Label11.Text = dr.GetString(6);
Label12.Text = dr.GetString(7);
TextBox1.Text = dr.GetString(3);
TextBox2.Text = dr.GetDecimal(4).ToString();
}
cn.Close();
}
}
You need to check page.Ispostback property in your page Load.
Here is your code.
protected void Page_Load(object sender, EventArgs e)
{
if(!Page.IsPostBack)
{
cnst = "Data Source=IBM369-R9WAKY5;Initial Catalog=anudatabase;Integrated Security=True";
cn = new SqlConnection(cnst);
cn.Open();
st = "select * from patient_db where unique_id = 123";
cmd = new SqlCommand(st, cn);
dr = cmd.ExecuteReader();
if (dr.Read())
{
Label9.Text = dr.GetString(1);
Label10.Text = dr.GetInt16(2).ToString();
Label11.Text = dr.GetString(6);
Label12.Text = dr.GetString(7);
TextBox1.Text = dr.GetString(3);
TextBox2.Text = dr.GetDecimal(4).ToString();
}
cn.Close();
}
}
When you click on button then it will first call PageLoad event. So it will again set your old value to textbox and then it will call update method. So Update method will update old value to database.

Categories

Resources