Retrieve database values to textboxes whenever listbox selected index changed - c#

so I just want to view the values from my database to some textboxes in my project whenever the selected index of listbox changes
I have these code but whenever I click an item on my listbox, none of the textboxes displays a data or anything
protected void ListBox1_SelectedIndexChanged(object sender, EventArgs e)
{
if (IsPostBack)
{
try
{
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionStringHRMS"].ConnectionString);
conn.Open();
string selectone = "SELECT * FROM Applicant WHERE ApplicationNo = '" + ListBox1.SelectedValue.ToString() + "'";
SqlCommand cmd = new SqlCommand(selectone, conn);
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
asln.Text = reader["LastName"].ToString();
asfn.Text = reader["FirstName"].ToString();
asmn.Text = reader["MiddleName"].ToString();
ashea.Text = reader["HEA"].ToString();
astitle.Text = reader["Title"].ToString();
aspos.Text = reader["Position"].ToString();
asaddress.Text = reader["Address"].ToString();
asbday.Text = reader["Birthday"].ToString();
asgender.Text = reader["Gender"].ToString();
asage.Text = reader["Age"].ToString();
asht.Text = reader["Height"].ToString();
aswt.Text = reader["Weight"].ToString();
asemail.Text = reader["Email"].ToString();
ascontact.Text = reader["ContactNumber"].ToString();
}
reader.Close();
conn.Close();
}
catch (Exception ex)
{
Response.Write(ex);
}
}
}

Related

SQL DataReader: Invalid attempt to read when no data is present to label

I am trying to use a SqlDataReader to run queries on two tables where the 1st column in the Selection table is a foreign key referencing to the Items table, and then display the results in labels, but I keep getting the error:
Invalid attempt to read when no data is present.
Here is my code:
public partial class Read : System.Web.UI.Page
{
SqlConnection conn = new SqlConnection(#"data source = localhost; integrated security = true; database = dev_handin1");
SqlCommand cmd = null;
SqlDataReader rdr = null;
string sqlsel = "SELECT MainItemId FROM Selection";
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
GetInfo();
}
}
private void GetInfo() {
try
{
cmd = new SqlCommand(sqlsel, conn);
conn.Open();
sqlsel = "SELECT * FROM Items WHERE ItemId = MyMainItem";
rdr = cmd.ExecuteReader();
var MyMainItem = rdr[0];
while (rdr.Read())
{
LabelCategory1.Text = rdr[1].ToString();
LabelHeadline1.Text = rdr[2].ToString();
LabelText1.Text = rdr[3].ToString();
LabelJoke1.Text = rdr[4].ToString();
}
}
catch (Exception ex)
{
LabelMessage1.Text = ex.Message;
}
finally
{
rdr.Close();
conn.Close();
}
}
}
}
I'm pretty new at this so please bear with me.

C# How to Update/Change the specific letter/number of a string in database

I ask these question coz i really don't know how i'm gonna do that and is it possible to do that?
What i want is to update/change here for example STA-100418-100 in database values, update/change the 100 based on the user input, like 50 it will be STA-100418-50.
Here's the provided image to be more precise
As you can see on the image, there's a red line, if user update the quantity as 60, In Codeitem STA-100418-100 should be STA-100418-60
I really have no idea on how to do that. I hope someone would be able to help me
here's my code for updating the quantity
private void btn_ok_Click(object sender, EventArgs e)
{
using (var con = SQLConnection.GetConnection())
{
using (var selects = new SqlCommand("Update Product_Details set quantity = quantity - #Quantity where ProductID= #ProductID", con))
{
selects.Parameters.Add("#ProductID", SqlDbType.VarChar).Value = _view.txt_productid.Text;
selects.Parameters.Add("#Quantity", SqlDbType.Int).Value = Quantity;
selects.ExecuteNonQuery();
}
}
}
Here's the code to get that format in codeitems
string date = DateTime.Now.ToString("MMMM-dd-yyyy");
string shortdate = DateTime.Now.ToString("-MMddy-");
private void Quantity_TextChanged(object sender, EventArgs e)
{
Code.Text = Supplier.Text.Substring(0, 3) + shortdate + Quantity.Text;
}
Here's what I use to update SQL-Server
public static DataTable GetSqlTable(string sqlSelect)
{
string conStr = ConfigurationManager.ConnectionStrings["connString"].ConnectionString;
DataTable table = new DataTable();
SqlConnection connection = new SqlConnection(conStr);
try
{
connection.Open();
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
if (connection.State != ConnectionState.Open)
{
return table;
}
SqlCommand cmd = new SqlCommand(sqlSelect, connection);
SqlDataAdapter adapter = new SqlDataAdapter(cmd);
try
{
adapter.Fill(table);
}
catch(Exception ex)
{
MessageBox.Show(ex.ToString());
throw;
}
connection.Close();
connection.Dispose();
return table;
}
public static void GetSqlNonQuery(string sqlSelect)
{
string newObject = string.Empty;
string strConn = ConfigurationManager.ConnectionStrings["connString"].ConnectionString;
SqlConnection connection = new SqlConnection(strConn);
connection.Open();
if (connection.State != ConnectionState.Open)
{
return;
}
try
{
SqlCommand cmd = new SqlCommand(sqlSelect, connection);
cmd.ExecuteNonQuery();
connection.Close();
connection.Dispose();
}
catch (Exception ex)
{
string x = ex.Message + ex.StackTrace;
throw;
}
}
Here's how to use it
DataTable dt = GetSqlTable("select Quantity from product where CodeItem = 'STA-100418-100'");
string strQuantity = dt.Rows[0]["Quantity"].ToString();
GetSqlNonQuery(string.Format("UPDATE product SET CodeItem = '{0}' WHERE = 'STA-100418-100'", strQuantity));
User will input everytime in the Quantity textbox, the textchanged event of Quantity will be hit and you will get new value everytime with the same date but with different quantity. So you can use the Code.Text to update the CodeDateTime value or you can use a global variable instead of Code.Text and use it to update the column.
string date = DateTime.Now.ToString("MMMM-dd-yyyy");
string shortdate = DateTime.Now.ToString("-MMddy-");
private void Quantity_TextChanged(object sender, EventArgs e)
{
Code.Text = Supplier.Text.Substring(0, 3) + shortdate + Quantity.Text;
}
using (var con = SQLConnection.GetConnection())
{
using (var selects = new SqlCommand("Update Product_Details set quantity = quantity - #Quantity, CodeItem = #Code where ProductID= #ProductID", con))
{
selects.Parameters.Add("#ProductID", SqlDbType.VarChar).Value = _view.txt_productid.Text;
selects.Parameters.Add("#Quantity", SqlDbType.Int).Value = Quantity;
selects.Parameters.Add("#Code", Code.Text);
}
}
as I understand it you need MSSQL String Functions
SELECT rtrim(left(Codeitem,charindex('-', Codeitem))) + ltrim(str(Quantity)) FROM ...
For detailed information
Using MySql, Substring the code item and then concatenate the quantity.
UPDATE Product_Details SET quantity = #quantity,CodeIem = CONCAT(SUBSTR(#code,1,11),#quantity) WHERE ProductID= #ProductID

ProductInsert() does not exist in current context

protected void Btn_CheckOut_Click(object sender, EventArgs e)
{
int result = 0;
Payment user = new Payment(txt_CardNumber.Text, txt_CardHolderName.Text, txt_ExpirationDate.Text, txt_Cvv.Text);
result = ProductInsert();
/* Session["CardNumber"] = txt_CardNumber.Text;
Session["CardHolderName"] = txt_CardHolderName.Text;
Session["ExpirationDate"] = txt_ExpirationDate.Text;
Session["Cvv"] = txt_Cvv.Text;*/
Response.Redirect("Payment Sucessful.aspx");
}
public int ProductInsert()
{
int result = 0;
string queryStr = "INSERT INTO CustomerDetails(CardNumber, CardHolderName, ExpirationDate, Cvv)"
+ "values (#CardNumber,#CardHolderName, #ExpirationDate, #Cvv)";
try
{
SqlConnection conn = new SqlConnection(connStr);
SqlCommand cmd = new SqlCommand(queryStr, conn);
cmd.Parameters.AddWithValue("#CardNumber", this.CardNumber);
cmd.Parameters.AddWithValue("#CardHolderName", this.CardHolderName);
cmd.Parameters.AddWithValue("#ExpirationDate", this.ExpirationDate);
cmd.Parameters.AddWithValue("#Cvv", this.Cvv);
conn.Open();
result += cmd.ExecuteNonQuery(); // Returns no. of rows affected. Must be > 0
conn.Close();
return result;
}
catch (Exception ex)
{
return 0;
}
}
}
I am trying to store credit card informations into database. I have created a productInsert() method and now I am trying to insert whatever values into the database.
This code is giving the error:
ProductInsert() does not exist in current context

Image.MemoryStream : Parameter not valid

When I'm trying to retrieve my image by combo box there show the massage . Parameter not valid
I was try many way but problem is same ..
Every time I run the code below, I get same massage.
private void cBoxSearch_SelectedIndexChanged(object sender, EventArgs e)
{
try
{
con = ConnectionController.GetInstance().GetConnection();
con.Open();
com = new SQLiteCommand("SELECT * FROM Stock WHERE ProductName = '" + cBoxSearch.Text + "' ", con);
myReader = com.ExecuteReader();
product prod = new product();
while (myReader.Read())
{
prod.proid = myReader[0].ToString();
prod.prodname = myReader[1].ToString();
prod.proMdl = myReader[2].ToString();
prod.serialN = myReader[3].ToString();
prod.byibgPr = myReader[4].ToString();
prod.sellPr = myReader[5].ToString();
prod.quantity = myReader[6].ToString();
tbxProductID.Text = prod.proid;
tbxName.Text =prod.prodname;
tbxModel.Text = prod.proMdl;
tbxserial.Text = prod.serialN;
tbxbyingprice.Text = prod.byibgPr;
tbxSellingprice.Text = prod.sellPr;
tbxQuantity.Text = prod.quantity;
prod.imgg = (byte[])(myReader[7] );
if (prod.imgg == null)
{
pBX.Image = null;
}
else
{
MemoryStream mstrm = new MemoryStream(prod.imgg);
Bitmap bmp = new Bitmap(mstrm);
}
}
con.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
com.Cancel();
con.Close();
}
Try to consult this question:
convert binary to bitmap using memory stream
Also, it might depend on DBType of the 8th column of the query.

Datagridview Column Index Returning 0 after Update

I Bind Data to a DataGridview using the following code
private void BindGrid()
{
try
{
string constr = "Data Source=INSPIRE-1;" +
"Initial Catalog=testdatabase;" +
"User id=testuser;" +
"Password=tester;";
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand("SELECT * FROM mytable", con))
{
cmd.CommandType = CommandType.Text;
using (SqlDataAdapter sda = new SqlDataAdapter(cmd))
{
using (DataTable dt = new DataTable())
{
sda.Fill(dt);
dataGridView1.DataSource = dt;
}
}
}
}
if (flag == false)
{
flag = true;
DataGridViewButtonColumn uninstallButtonColumn = new DataGridViewButtonColumn();
uninstallButtonColumn.Name = "Edit";
uninstallButtonColumn.Text = "Edit";
dataGridView1.Columns.Insert(4, uninstallButtonColumn);
}
}
catch (Exception error)
{
MessageBox.Show(error.Message);
}
}
I Update the selected record by hooking to a button click event in the datagridview row like this
void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
{
if (e.ColumnIndex ==4)
{
button4.Enabled = false;
try
{
orderId = (string)dataGridView1.SelectedCells[0].OwningRow.Cells[0].Value;
using (SqlConnection conn = new SqlConnection(constr))
{
try
{
conn.Open();
SqlDataReader myReader = null;
string commandText = "select * from mytable where name= #name";
SqlCommand command = new SqlCommand(commandText, conn);
command.Parameters.AddWithValue("#name", orderId);
myReader = command.ExecuteReader();
while (myReader.Read())
{
textBox1.Text = myReader["name"].ToString();
textBox2.Text = myReader["age"].ToString();
textBox3.Text = myReader["phone"].ToString();
textBox4.Text = myReader["address"].ToString();
}
}
catch (Exception err)
{
MessageBox.Show(err.Message);
}
}
}
catch (Exception error)
{
}
}
}
Now i update the values using the code below
private void button5_Click(object sender, EventArgs e)
{
using (SqlConnection conn = new SqlConnection(constr))
{
conn.Open();
using (SqlCommand cmd =
new SqlCommand("UPDATE mytable SET name=#NewName,age=#NewAge,phone=#NewPhone,Address=#NewAddress" +
" WHERE name=#oldname", conn))
{
cmd.Parameters.AddWithValue("#NewName", textBox1.Text);
cmd.Parameters.AddWithValue("#NewAge", textBox2.Text);
cmd.Parameters.AddWithValue("#NewPhone", textBox3.Text);
cmd.Parameters.AddWithValue("#NewAddress", textBox4.Text);
cmd.Parameters.AddWithValue("#oldname", orderId);
try
{
int rows = cmd.ExecuteNonQuery();
MessageBox.Show("Updated Successfully");
}
catch (SqlException ex)
{
MessageBox.Show(ex.Message);
}
}
}
BindGrid();
textBox1.Clear();
textBox2.Clear();
textBox3.Clear();
textBox4.Clear();
button4.Enabled=true;
}
But after i click the Update Button then click on the Button Column corresponding to a Row e.ColumnIndex always returns 0.
What im i doing wrong?
UPDATE :
Please see the screenshot
Rahul's Answer will work but looks like orderId = (string)dataGridView1.SelectedCells[0].OwningRow.Cells[0].Value; should be modifiled to get Cells[1].Value and not 0 as 0 is the button cell from 2nd time onwards. But for 1st time you need to use 0 as then button is at index 4. Try below changes.
As far as I understand, issue is after update, you call the BindGrid again and since flag is true it just sets the datasource again for the grid and not generating button again thus button gets moved to index 0 followed by the datatable columns.
Another way to solve is modify your code a bit like
dataGridView1.Columns.Insert(0, uninstallButtonColumn);
dataGridView1.Columns[0].DisplayIndex = 4;
And then in CellClick event check for e.ColumnIndex == 0. This help you in showing the button at the position you want and always the click work as the columnindex never changes.
you can check button index like below without comparing its index:
private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
var senderGrid = (DataGridView)sender;
if (senderGrid.Columns[e.ColumnIndex] is DataGridViewButtonColumn &&
e.RowIndex >= 0)
{
//TODO - Button Clicked - Execute Code Here
}
}

Categories