I have two textboxes and two buttons on one site. The problem is that this second textbox and second button doesn't work. First textbox+button doing well:
int NoOfDigTextBoxEngine;
protected void TextBoxADDEngine_TextChanged(object sender, EventArgs e)
{
NoOfDigTextBoxEngine = TextBoxADDEngine.Text.Length;
}
protected void ButtonADDEngine_Click(object sender, EventArgs e)
{
String strConnString = ConfigurationManager.ConnectionStrings["AppConnectionString"].ConnectionString;
using (SqlConnection con = new SqlConnection(strConnString))
{
SqlCommand cmd = new SqlCommand();
SqlDataAdapter sda = new SqlDataAdapter();
DataSet ds = new DataSet();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "SELECT Engine, Created, LastChange, WhoInserted, WhoLastModified, Disable FROM PartsEngine";
cmd.Connection = con;
sda.SelectCommand = cmd;
if (FillWhoIsLogged > 0) // ----------------Wypełnianie tebeli kiedy jest ktos zalogowany--- //
{
if (NoOfDigTextBoxEngine == 7)
{
try
{
Convert.ToInt32(TextBoxADDEngine.Text);
con.Open();
cmd.CommandText = ("INSERT INTO PartsEngine ([Engine], [Created], [WhoInserted], [Disabled]) VALUES ('" + TextBoxADDEngine.Text + "', GETDATE(), '" + FillWhoIsLogged + "', '1');");
cmd.ExecuteNonQuery();
GridView3.DataBind();
TextBoxADDEngine.Text = string.Empty;
con.Close();
}
catch
{
Response.Write("<script type='text/javascript'> alert('Nr Silnika może zawierać jedynie cyfry.')</script>");
TextBoxADDEngine.Text = string.Empty;
}
}
else
{
Response.Write("<script type='text/javascript'> alert('Nr Silnika musi mieć 7 cyfr.Podano: " + NoOfDigTextBoxEngine + " ')</script>");
TextBoxADDEngine.Text = string.Empty;
}
}
}
}
But the second (is the same) don't want to work.
int NoOfDigTextBoxGear;
protected void TextBoxADDGear_TextChanged(object sender, EventArgs e)
{
NoOfDigTextBoxGear = TextBoxADDGear.Text.Length;
}
protected void ButtonADDGear_Click(object sender, EventArgs e)
{
String strConnString = ConfigurationManager.ConnectionStrings["AppConnectionString"].ConnectionString;
using (SqlConnection con = new SqlConnection(strConnString))
{
SqlCommand cmd = new SqlCommand();
SqlDataAdapter sda = new SqlDataAdapter();
DataSet ds = new DataSet();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "SELECT Gear, Created, LastChange, WhoInserted, WhoLastModified, Disable FROM PartsGear";
cmd.Connection = con;
sda.SelectCommand = cmd;
if (FillWhoIsLogged > 0) // ----------------Wypełnianie tebeli kiedy jest ktos zalogowany--- //
{
if (NoOfDigTextBoxGear == 7)
{
try
{
Convert.ToInt32(TextBoxADDGear.Text);
con.Open();
cmd.CommandText = ("INSERT INTO PartsGear ([Gear], [Created], [WhoInserted], [Disabled]) VALUES ('" + TextBoxADDGear.Text + "', GETDATE(), '" + FillWhoIsLogged + "', '1');");
cmd.ExecuteNonQuery();
GridView5.DataBind();
TextBoxADDGear.Text = string.Empty;
con.Close();
}
catch
{
Response.Write("<script type='text/javascript'> alert('Nr Skrzyni może zawierać jedynie cyfry.')</script>");
TextBoxADDGear.Text = string.Empty;
}
}
else
{
Response.Write("<script type='text/javascript'> alert('Nr Skrzyni musi mieć 7 cyfr. Podano: "+ NoOfDigTextBoxGear +" ')</script>");
TextBoxADDGear.Text = string.Empty;
}
}
}
}
When i write something in second textbox and then click button- always NoOfDigTextBoxGear = 0...why?
It's not make any sense for me because this code(for second textbox and button) is the same like the the first one(for first textbox and button).
Oh... i just saw this:
<asp:TextBox ID="TextBoxADDGear" runat="server" Visible="False"
Width="96px"></asp:TextBox>
I didn't add ontextchanged(!)
ontextchanged="TextBoxADDGear_TextChanged"
Now everything is ok.
Related
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 :
Basically, what I want to delete an entry form a dataviewtable which pulls data through from MySql. I thought this would be done fairly by effectively copying the modify code and substituting it for 'DELETE'. However, from the code below, you can clearly see that hasn't worked. I will copy most of my code for you:
private void button1_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection("Data Source=DESKTOP-HNR3NJB\\mysql;Initial Catalog=stock;Integrated Security=True");
var sqlQuery = "";
if (IfProductsExists(con, textboxProductID.Text))
{
con.Open();
sqlQuery = #"DELETE FROM [Products] WHERE [ProductID] = '" + textboxProductID.Text + "'";
SqlCommand cmd = new SqlCommand(sqlQuery, con);
cmd.ExecuteNonQuery();
con.Close();
}
else
{
MessageBox.Show("Record doesn't exist!", "ERROR:", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
//Reading Data
LoadData();
}
So that's the delete button's code now for the add button and load data function
Add button:
private void button2_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(#"Data Source=DESKTOP-HNR3NJB\mysql;Initial Catalog=stock;Integrated Security=True");
//insert logic
con.Open();
if(textboxProductID.Text == "" || textboxProductName.Text == "")
{
MessageBox.Show("You have to enter either a product ID or product name", "Error:", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
else
{
bool status = false;
if (comboboxStatus.SelectedIndex == 0)
{
status = true;
}
else
{
status = false;
}
var sqlQuery = "";
if (IfProductsExists(con, textboxProductID.Text))
{
sqlQuery = #"UPDATE [Products] SET [ProductName] = '" + textboxProductName.Text + "' ,[ProductStatus] = '" + status + "' WHERE [ProductID] = '" + textboxProductID.Text + "'";
}
else
{
sqlQuery = #"INSERT INTO [Stock].[dbo].[Products] ([ProductID],[ProductName],[ProductStatus]) VALUES
('" + textboxProductID.Text + "','" + textboxProductName.Text + "','" + status + "')";
}
SqlCommand cmd = new SqlCommand(sqlQuery, con);
cmd.ExecuteNonQuery();
con.Close();
textboxProductID.Clear();
textboxProductName.Clear();
LoadData();
}
}
LoadData function:
public void LoadData()
{
SqlConnection con = new SqlConnection(#"Data Source=DESKTOP-HNR3NJB\mysql;Initial Catalog=stock;Integrated Security=True");
//reading data from sql
SqlDataAdapter sda = new SqlDataAdapter("Select * From [stock].[dbo].[Products]", con);
DataTable dt = new DataTable();
sda.Fill(dt);
dataGridView1.Rows.Clear();
foreach (DataRow item in dt.Rows)
{
int n = dataGridView1.Rows.Add();
dataGridView1.Rows[n].Cells[0].Value = item["ProductID"].ToString();
dataGridView1.Rows[n].Cells[1].Value = item["ProductName"].ToString();
if ((bool)item["ProductStatus"])
{
dataGridView1.Rows[n].Cells[2].Value = "Active";
}
else
{
dataGridView1.Rows[n].Cells[2].Value = "Deactive";
}
}
}
You're going to need the IfProductsExists method too:
private bool IfProductsExists(SqlConnection con, string productCode)
{
SqlDataAdapter sda = new SqlDataAdapter("Select 1 From [Products] WHERE [ProductID]='" + productCode + "'", con);
DataTable dt = new DataTable();
if (dt.Rows.Count > 0)
return true;
else
return false;
}
It's going to be an inventory system that's going to be used at work for the sale and inventory management of IT equipment.
This is how my code really looks and performs. I have been trying to do filtering data according to comboboxes that I fill from the database and then to show data on the datagridview. Because I'm a beginner in coding, it has been really hard to write the combobox populating codes. I really searched in internet, read most of the titles. Is there any way to do this after all selections are done and maybe with the text is written in textbox and the search button (I created) clicked according to
the selections datagridview shows.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
namespace KPI_Tool
{
public partial class SearchForm : Form
{
static SqlConnection conn = new SqlConnection(#"Data Source=(LocalDB)\v11.0;AttachDbFilename=C:\Users\010495\Desktop\KPI_Tool\KPI_Tool\KPI_Store.mdf;Integrated Security=True");
public SearchForm()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
// TODO: This line of code loads data into the 'kPI_StoreDataSet1.Store' table. You can move, or remove it, as needed.
this.myAdapter.Fill(this.myDataSet.Store);
}
private void Group_DropDown(object sender, EventArgs e)
{
conn.Open();
comboBox1.Items.Clear();
SqlCommand cmd = conn.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "SELECT DISTINCT GroupN FROM Store WHERE GroupN IS NOT NULL";
cmd.ExecuteNonQuery();
DataTable dt = new DataTable();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);
foreach (DataRow dr in dt.Rows)
{
comboBox1.Items.Add(dr["GroupN"].ToString());
}
conn.Close();
}
private void Tech_DropDown(object sender, EventArgs e)
{
conn.Open();
comboBox2.Items.Clear();
SqlCommand cmd = conn.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "SELECT DISTINCT Tech_Area FROM Store WHERE Tech_Area IS NOT NULL";
cmd.ExecuteNonQuery();
DataTable dt = new DataTable();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);
foreach (DataRow dr in dt.Rows)
{
comboBox2.Items.Add(dr["Tech_Area"].ToString());
}
conn.Close();
}
private void Level_DropDown(object sender, EventArgs e)
{
conn.Open();
comboBox3.Items.Clear();
SqlCommand cmd = conn.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "SELECT DISTINCT LevelOf FROM Store WHERE LevelOf IS NOT NULL";
cmd.ExecuteNonQuery();
DataTable dt = new DataTable();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);
foreach (DataRow dr in dt.Rows)
{
comboBox3.Items.Add(dr["LevelOf"].ToString());
}
conn.Close();
}
private void Domain_DropDown(object sender, EventArgs e)
{
conn.Open();
comboBox4.Items.Clear();
SqlCommand cmd = conn.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "SELECT DISTINCT DomainN FROM Store WHERE DomainN IS NOT NULL";
cmd.ExecuteNonQuery();
DataTable dt = new DataTable();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);
foreach (DataRow dr in dt.Rows)
{
comboBox4.Items.Add(dr["DomainN"].ToString());
}
conn.Close();
}
private void Type_DropDown(object sender, EventArgs e)
{
conn.Open();
comboBox5.Items.Clear();
SqlCommand cmd = conn.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "SELECT DISTINCT TypeN FROM Store WHERE TypeN IS NOT NULL";
cmd.ExecuteNonQuery();
DataTable dt = new DataTable();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);
foreach (DataRow dr in dt.Rows)
{
comboBox5.Items.Add(dr["TypeN"].ToString());
}
conn.Close();
}
private void Severity_DropDown(object sender, EventArgs e)
{
conn.Open();
comboBox6.Items.Clear();
SqlCommand cmd = conn.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "SELECT DISTINCT Severity FROM Store WHERE Severity IS NOT NULL";
cmd.ExecuteNonQuery();
DataTable dt = new DataTable();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);
foreach (DataRow dr in dt.Rows)
{
comboBox6.Items.Add(dr["Severity"].ToString());
}
conn.Close();
}
private void AlertTB_Click(object sender, MouseEventArgs e)
{
AlertTB.Clear();
}
private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
}
private void ListB_Click(object sender, EventArgs e)
{
}
private void ClearB_Clicked(object sender, EventArgs e)
{
comboBox1.SelectedIndex = -1;
comboBox2.SelectedIndex = -1;
comboBox3.SelectedIndex = -1;
comboBox4.SelectedIndex = -1;
comboBox5.SelectedIndex = -1;
comboBox6.SelectedIndex = -1;
AlertTB.Clear();
AlertTB.Text = "Write Here..";
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
conn.Open();
myBindingSource.Filter = "GroupN= '{0}'"+comboBox1.SelectedItem.Te;
conn.Close();
}
}
}
Here is my User Interface. I'm using Visual Studio Professional 2013. Please explain to me with very basic sentences. I want to learn the logic, the structure behind the code.
If you want to filter the gridview according to the text you entered in the textbox you can refer to my blog post
http://dotnetsolutionsbyankit.blogspot.in/2013/04/filter-gridview-as-you-type-in-textbox.html
so you will get an idea how to do it.
If you face any problem let me know in comment.
public static DataSet SQLGetData(string connectionString, string commandString)
{
using (SqlConnection connection = new SqlConnection(connectionString))
{
DataSet DS = new DataSet();
DataTable DT = new DataTable("Table1");
try
{
connection.Open();
SqlCommand command = new SqlCommand(commandString, connection);
//command.CommandTimeout = 3000;
SqlDataReader read = command.ExecuteReader();
DS.Tables.Add(DT);
DS.Load(read, LoadOption.PreserveChanges, DS.Tables[0]);
}
catch (SqlException e)
{
System.Windows.Forms.MessageBox.Show(e.Message);
}
finally
{
connection.Close();
}
return DS;
}
}
private void SetFilter()
{
string command = "SELECT * FROM Store";
int count = 0;
if (comboBox1.Text != "")
{
command = command + " WHERE GroupN = '" + comboBox1.Text + "'";
count = count + 1;
}
if (comboBox2.Text != "")
{
if (count == 0)
{
command = command + " WHERE Tech_Area = '" + comboBox2.Text + "'";
}
else
{
command = command + " AND Tech_Area = '" + comboBox2.Text + "'";
}
count = count + 1;
}
if (comboBox3.Text != "")
{
if (count == 0)
{
command = command + " WHERE LevelOf = '" + comboBox3.Text + "'";
}
else
{
command = command + " AND LevelOf = '" + comboBox3.Text + "'";
}
count = count + 1;
}
// comboBox4, comboBox5, comboBox6
string connStr; //Connection string;
DataSet DS = new DataSet();
DS = SQLGetData(connStr, command);
DataGridView1.DataSource = DS.Tables[0];
}
I have two combo boxes "Year" & "Amount" on the top of them I do get values for user info, because there are text boxes when called with user ID text boxes fill up with correct data.
The two combo boxes are also filled with correct data but I have to manually select year and the amount corresponding to it.
I need help in when I call the data "Year" & "Amount" should appear visible in the combo box. When I select a Year then the Amount should change accordingly. Last but not the least my reset is not clearing the combo boxes.
using System;
using System.Windows.Forms;
using System.Data.SqlClient;
using System.Data;
namespace dss
{
public partial class Form1 : Form
{
SqlConnection con = new SqlConnection("Data Source=USER-PC\\sqlexpress;Initial Catalog=JG_Test;Integrated Security=True");
public Form1()
{
InitializeComponent();
}
private void btnSearch_Click(object sender, EventArgs e)
{
cmbYear.Items.Clear();
string sql = "";
con.Open();
SqlCommand cmd = new SqlCommand();
try
{
sql += "SELECT m.MemberId, m.Name, m.Address, m.Cellular, m.Email, p.PaymentId, p.Year, p.Amount from Members as m";
sql += " INNER JOIN Payments as p ON m.MemberId = p.MemberId";
sql += " WHERE m.MemberId = '" + tbID.Text + "' ORDER BY p.Year ASC";
cmd.Connection = con;
cmd.CommandText = sql;
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
con.Close();
if(dt.Rows.Count >0)
{
for(int i = 0; i<=dt.Rows.Count -1;i++)
{
tbID.Text = dt.Rows[i]["MemberId"].ToString();
tbName.Text = dt.Rows[i]["Name"].ToString();
tbCellular.Text = dt.Rows[i]["Cellular"].ToString();
tbEmail.Text = dt.Rows[i]["Email"].ToString();
tbAddress.Text = dt.Rows[i]["Address"].ToString();
cmbAmount.Items.Add(dt.Rows[i]["Amount"].ToString());
cmbYear.Items.Add(dt.Rows[i]["Year"].ToString());
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message.ToString());
}
}
//This part displaying og the existing data from all the fileds corrssponding within the database//
private void btnAdd_Click(object sender, EventArgs e)
{
{
con.Open();
string Sql = "INSERT INTO Members ( MemberId, Name, Cellular, Email, Address ) VALUES " + " (#Id, #name, #cell, #email, #address)";
using (SqlCommand cmd = new SqlCommand(Sql, con))
{
cmd.CommandText = Sql;
cmd.Parameters.AddWithValue("#Id", tbID.Text);
cmd.Parameters.AddWithValue("#name", tbName.Text);
cmd.Parameters.AddWithValue("#cell", tbCellular.Text);
cmd.Parameters.AddWithValue("#email", tbCellular.Text);
cmd.Parameters.AddWithValue("#address", tbAddress.Text);
cmd.ExecuteNonQuery();
Sql = "INSERT INTO Payments ( MemberId, [Year], [Amount] ) VALUES " + " (#Id, Amount, Year)";
cmd.Parameters.Clear();
cmd.CommandText = Sql;
cmd.Parameters.AddWithValue("#Id", tbID.Text);
cmd.Parameters.AddWithValue("#year", cmbYear.Text);
cmd.Parameters.AddWithValue("#amount", cmbAmount.Text);
cmd.ExecuteNonQuery();
MessageBox.Show("Data Added");
tbID.Clear(); tbName.Clear(); tbCellular.Clear(); tbEmail.Clear(); tbAddress.Clear(); cmbYear.Items.Clear(); cmbAmount.Items.Clear();
con.Close();
}
}
}
//This part represents adding of new input data from all the fileds into the database//
private void btnUpdate_Click(object sender, EventArgs e)
{
try
{
SqlCommand cmd = new SqlCommand();
string Sql = "UPDATE Members SET MemberId = '" + tbID.Text + "', Name = '" + tbName.Text + "', Cellular = '" + tbCellular.Text + "', Email = '" + tbEmail.Text + "', Address = '" + tbAddress.Text + "' WHERE MemberId = '" + tbID.Text + "' ";
cmd.CommandText = Sql;
cmd.Connection = con;
con.Open();
cmd.ExecuteNonQuery();
con.Close();
Sql = "UPDATE Payments SET MemberId = '" + tbID.Text + "', Year = '" + cmbYear.Text + "', Amount = '" + cmbAmount.Text + "' WHERE MemberId = '" + tbID.Text + "' ";
cmd.CommandText = Sql;
cmd.Connection = con;
con.Open();
cmd.ExecuteNonQuery();
con.Close();
MessageBox.Show("Data Updated");
tbID.Clear(); tbName.Clear(); tbAddress.Clear(); tbCellular.Clear(); tbEmail.Clear(); cmbYear.Items.Clear(); cmbAmount.Items.Clear();
}
catch (Exception error)
{
MessageBox.Show(error.ToString());
}
}
//This part represents deleteing of input data from all the fileds into the database//
private void btnDelete_Click(object sender, EventArgs e)
{
try
{
SqlCommand cmd = new SqlCommand();
string Sql = "DELETE FROM Members WHERE MemberId = '" + tbID.Text + "' ";
cmd.CommandText = Sql;
cmd.Connection = con;
con.Open();
cmd.ExecuteNonQuery();
con.Close();
Sql = "DELETE FROM Payments WHERE MemberId = '" + tbID.Text + "' ";
cmd.CommandText = Sql;
cmd.Connection = con;
con.Open();
cmd.ExecuteNonQuery();
tbID.Clear(); tbName.Clear(); tbAddress.Clear(); tbCellular.Clear(); tbEmail.Clear(); cmbYear.Items.Clear(); cmbAmount.Items.Clear();
MessageBox.Show("Data Deleted");
con.Close();
}
catch (Exception error)
{
MessageBox.Show(error.ToString());
}
}
//This part represents clearing of input data from all the fileds//
private void btnReset_Click(object sender, EventArgs e)
{
tbID.Clear(); tbName.Clear(); tbAddress.Clear(); tbCellular.Clear(); tbEmail.Clear(); cmbYear.Items.Clear(); cmbAmount.Items.Clear();
}
//This part represents shuting down the application//
private void btnExit_Click(object sender, EventArgs e)
{
Application.Exit();
}
}
}
I would be inclined to simplify things a bit. Treat the personal data and the finance data as 2 parts.
Firstly, request the personal data - keep it simple
private void btnSearch_Click(object sender, EventArgs e)
{
string sql = "SELECT MemberId, Name, Address, Cellular, Email FROM Members WHERE MemberId = #Id";
SqlConnection con = new SqlConnection("myconnectionstring");
SqlCommand cmd = new SqlCommand(sql,con);
cmd.Parameters.Add("#Id",SqlDbType.Int).Value = tbID.Text;
DataTable dt = new DataTable();
try
{
con.Open();
dt.Load(cmd.ExecuteReader());
con.Close();
}
catch (Exception ex)
{
con.Close();
Console.WriteLine(ex.Message);
}
tbID.Text = dt.Rows[0]["MemberId"].ToString();
tbName.Text = dt.Rows[0]["Name"].ToString();
tbCellular.Text = dt.Rows[0]["Cellular"].ToString();
tbEmail.Text = dt.Rows[0]["Email"].ToString();
tbAddress.Text = dt.Rows[0]["Address"].ToString();
}
Once thats done, move on to second part - the years/amounts combo (which is almost identical code)
string sql = "SELECT Year, Amount FROM Payments WHERE MemberId = #Id"
SqlConnection con = new SqlConnection("myconnectionstring");
SqlCommand cmd = new SqlCommand(sql,con);
cmd.Parameters.Add("#Id",SqlDbType.Int).Value = tbID.Text;
DataTable dt = new DataTable();
try
{
con.Open();
dt.Load(cmd.ExecuteReader());
con.Close();
}
catch (Exception ex)
{
con.Close();
Console.WriteLine(ex.Message);
}
cmbYear.DataSource = dt;
cmbYear.DisplayMember = "Year";
cmbYear.ValueMember = "Amount";
And finally, tell the textbox what it needs to read by using
private void cmbYear_SelectionChangeCommitted(object sender, EventArgs e)
{
amountTxt.Text = cmbYear.SelectedValue.ToString();
}
in the combobox's SelectionChangeCommitted event
And that should have you sorted!
Can anybody tell me why my database isn't updating? Here's my code:
protected void editSection_selected(object sender, EventArgs e) {
int index = grdPhone.SelectedIndex;
GridViewRow row = grdPhone.Rows[index+1];
string values = ((DropDownList)sender).SelectedValue;
int tempVal = Convert.ToInt32(values);
int caseage = Convert.ToInt32(keyId);
int value = tempVal;
/*OleDbConnection con = new OleDbConnection(strConnstring);
//string query = "Update Categories set HRS_LEVEL_AMOUNT=" + tempVal + " where parent_id=65 and ID=" + caseage;
string query = "Delete HRS_LEVEL_AMOUNT from Categories where parent_id=65 and id=" + caseage;
OleDbCommand cmd = new OleDbCommand(query, con);
con.Open();
cmd.ExecuteNonQuery();
con.Dispose();
cmd.Dispose();
con.Close();
accPhoneNumbers.UpdateCommand = "Update Categories set HRS_LEVEL_AMOUNT=" + tempVal + " where parent_id=65 and ID=" + caseage;
*/
string str = "UPDATE Categories SET HRS_LEVEL_AMOUNT = ? WHERE ID=?";
using (OleDbConnection con = new OleDbConnection(strConnstring))
{
using (OleDbCommand cmd = new OleDbCommand(str, con))
{
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("HRS_LEVEL_AMOUNT", tempVal);
cmd.Parameters.AddWithValue("ID", caseage);
con.Open();
cmd.ExecuteNonQuery();
}
}
Label1.Text += " editSection Success! (B) " + tempVal;
}
The commented part is my first solution (including the accPhoneNumbers.UpdateCommand).
I really need your help guys.
I hope this can help you:
string str = "UPDATE Categories SET HRS_LEVEL_AMOUNT = #value1 WHERE ID=#value2";
using (OleDbConnection con = new OleDbConnection(strConnstring))
{
using (OleDbCommand cmd = new OleDbCommand(str, con))
{
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("#value1", tempVal);
cmd.Parameters.AddWithValue("#value2", caseage);
con.Open();
cmd.ExecuteNonQuery();
con.close();
}
}
For more information you can visit this video