Add referenced name instead of ID from comobox - c#

I have 2 tables. First has column (categoryID) that is foreign key for categoryID in second table.Second table has 2 columns (categoryID, categoryName). After bit struggling I've displayed in combobox categoryName instead of categoryID. But now when I want to choose from existing categoryName that is already created (displayed in dropdown in combobox), is not possible because I have to type there int not string format. I'm beginner in programming
con.Open();
string cmddt = "insert into wallettbl(sum, date, categoryID, type)
values ('" + textBox1.Text + "','" + textBox2.Text + "','" +
comboBox1.Text + "', '" + type + "')";
SqlCommand com = new SqlCommand(cmddt, con);
com.ExecuteNonQuery();
How to write code if I want to add string (from combobox) instead of int, but in first table will be added categoryID which is referenced to categoryName.
EDIT: added code for combobox
con.Open();
string cmddt = "select categoryNAME from categoryTbl";
SqlCommand com = new SqlCommand(cmddt, con);
SqlDataAdapter da = new SqlDataAdapter(cmddt, con);
DataSet ds = new DataSet();
da.Fill(ds);
com.ExecuteNonQuery();
con.Close();

change the query to load the categories as below:
string cmddt = "select categoryID, categoryNAME from categoryTbl";
Set the datasource for comboBox1 as below:
comboBox1.DataSource = dt;
comboBox1.DisplayMember = "categoryNAME";
comboBox1.ValueMember = "categoryID";
and finally modify the code to insert data into the wallettbl as follows:
string cmddt=
#"INSERT INTO WALLETTBL(sum, date, categoryID, type)
VALUES (#Sum, #Date, #CategoryId, #Type);";
using (SqlConnection conn = new SqlConnection(ConnectionString))
{
using (SqlCommand cmd = new SqlCommand(insertQuery, conn))
{
cmd.Parameters.Add("#Sum", SqlDbType.Int).Value = textBox1.Text;
cmd.Parameters.Add("#Date", SqlDbType.DateTime).Value = textBox2.Text;
cmd.Parameters.Add("#CategoryId", SqlDbType.Int).Value = Convert.ToInt32(comboBox1.SelectedValue);
cmd.Parameters.Add("#Type", SqlDbType.Varchar).Value = type;
await conn.OpenAsync();
await cmd.ExecuteNonQueryAsync();
}
}

Related

Retrieve data from a another table and insert into a another

I'm trying to retrieve data from a table according to the ID number and insert it to another table. The program is in C# and database in MySQL.
The retrieving table name is student_dt and the table name i want to insert is student_att
Here's what I'm doing so far
private void button1_Click(object sender, EventArgs e)
{
cmd = new MySqlCommand();
cmd.CommandText = "Insert into student_att values(`id`, `nic`, `name`, `address`, `number`, `batch`)";
string Query1 = "select * from student_dt where id like '" + textBox1.Text + "%'";
if (textBox1.Text == "")
{
MessageBox.Show("Please provide all data");
}
else
{
con.Open();
cmd.Connection = con;
cmd.ExecuteNonQuery();
con.Close();
MessageBox.Show("Data Inserted");
string Query = "select * from student_att ;";
MySqlCommand MyCommand2 = new MySqlCommand(Query, con);
MySqlDataAdapter MyAdapter = new MySqlDataAdapter();
MyAdapter.SelectCommand = MyCommand2;
DataTable dTable = new DataTable();
MyAdapter.Fill(dTable);
dataGridView2.DataSource = dTable;
}
You can do from one query
string query = "insert into student_att (`id`, `nic`, `name`, `address`,
`number`, `batch`) select * from student_dt where id like '" + textBox1.Text + "%'"

How to make insert operation using MySqlDataAdapter in ASP.NET

I am able to perform insert using the code which I've made comments here. How to achieve the same using MySqlDataAdapter ? The code I've written isn't working.
string sid, sname;
sid = Request.QueryString["StudentId"].ToString();
sname = Request.QueryString["StudentName"].ToString();
MySqlDataAdapter da = new MySqlDataAdapter("insert into tblStudent (StudentId, StudentName) values ('" + sid.ToString() + "', '" + sname.ToString() + "')", con);
// con.Open();
// MySqlCommand cmd = con.CreateCommand();
// cmd.CommandType = CommandType.Text;
// cmd.CommandText = "insert into tblStudent (StudentId, StudentName) values('" + sid.ToString() + "', '" + sname.ToString() + "')";
// cmd.ExecuteNonQuery();
// con.Close();
Help with suggestions.
To insert a single record you could simply use the MySqlCommand instead of a MySqlDataAdapter. MySqlDataAdapter has many functionality and allows you to execute Insert, Update and Delete actions on your data but you first need to reach the server to fill a DataTable, then add a new record to the datatable and finally call Update. Not worth the effort if you just need to insert a single record
However if you really want to try to use an DataAdapter then you need this code
string sid, sname;
sid = Request.QueryString["StudentId"].ToString();
sname = Request.QueryString["StudentName"].ToString();
string selectText = "SELECT studentID, StudentName FROM tblStudent WHERE 1=0";
using(MySqlDataAdapter da = new MySqlDataAdapter(selectText, con))
{
MySqlCommandBuilder bd = new MySqlCommandBuilder(da);
DataTable dt = new DataTable();
da.Fill(dt);
// This is important, because Update will work only on rows
// present in the DataTable whose RowState is Added, Modified or Deleted
dt.Rows.Add(sid, sname);
da.Update(dt);
}

Using Drop-down with Check-boxes in Asp.net

I have 2 drop-down boxes and i want the first drop-down to filter the 2nd one like cascading so the first one has check-boxes and i want to pass the selected items from the first one to the 2nd but getting a "syntax error". I run it into debug mode and the output result looks like this
CommandText "select id, name FROM myTable where id in (''CKU019','CW5036'') "
and it seems there is extra apostrophe near CKU019. Here is my code
protected void bindDDL()
{
string selectedValues = string.Empty;
foreach (ListItem item in ddchkCountry.Items)
{
if (item.Selected)
selectedValues += "'" + item.Value + "',";
}
if (selectedValues != string.Empty)
selectedValues = selectedValues.Remove(selectedValues.Length - 1);
SqlConnection con = new SqlConnection(strConnString);
con.Open();
SqlCommand cmd = new SqlCommand("select id, name FROM myTable where id in ('" + selectedValues + "')", con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
con.Close();
facDDL.DataSource = ds;
facDDL.DataTextField = "name";
facDDL.DataValueField = "id";
facDDL.DataBind();
}
Remove the extra ' wrapping your selected values...
SqlCommand cmd = new SqlCommand("select id, name FROM myTable where id in (" + selectedValues + ")", con);

How to display two different columns in one combobox

I want to display the two different columns in one particular combobox. When I run it the Customer ID will display. Here is my code.
void GetRecords2()
{
SqlCommand cmd = new SqlCommand();
cmd.Connection = cn;
cmd.CommandText = "SELECT CustomerID, firstname
+ ',' + lastname FROM Customer";
SqlDataAdapter adp = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
adp.Fill(ds, "Customer");
cboName.DataSource = ds;
cboName.DisplayMember = "Customer.firstname, Customer.lastname";
cboName.ValueMember = "Customer.CustomerID";
}
I see you already are creating a single result column containing the "combined" value. That's have the battle.
But, you need to give your column a name (notice the AS FullName alias):
cmd.CommandText = "SELECT CustomerID, firstname + ',' + lastname AS FullName " +
"FROM Customer";
So you can reference it later by name:
cboName.DisplayMember = "FullName";
This will work. I find that binding a Dictionary to a ComboBox has much more predictable results.
My approach omits the extra SQL syntax, DataSet, and SqlDataAdapter.
Instead I use the SqlDataReader to place the desired information into a Dictionary and then I bind that Dictionary as the DataSource of the Combobox.
void GetRecords2()
{
Dictionary <int, string> myDict = new Dictionary<int, string>();
SqlCommand cmd = new SqlCommand();
cmd.Connection = cn;
cmd.CommandText = "SELECT CustomerID, firstname, lastname FROM Customer";
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
myDict.Add(Convert.ToInt32(reader["CustomerID"]),
reader["firstname"].ToString() + " " + reader["lastname"].ToString());
}
if (myDict.Count > 0)
{
cboName.DataSource = new BindingSource(myDict, null);
cboName.DisplayMember = "Value";
cboName.ValueMember = "Key";
}
}
Check this:
void GetRecords2()
{
SqlCommand cmd = new SqlCommand();
cmd.Connection = cn;
cmd.CommandText = "SELECT CustomerID, firstname
+ ',' + lastname FullName FROM Customer";
SqlDataAdapter adp = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
adp.Fill(ds, "Customer");
cboName.DataSource = ds;
cboName.DisplayMember = "FullName";
cboName.ValueMember = "CustomerID";
}
To get selected value :
string customerid = cboName.SelectedValue.toString(); //CustomerID: 1
To get selected item
string fullname = cboName.SelectedItem.Text; //FullName : John Hawkins
Best Regards

Display SQL query result in a label in asp.net

I'm trying to display the SQL query result in a label but it's not showing. This is my code:
string result = "SELECT ACTIVE FROM [dbo].[test] WHERE ID = '" + ID.Text + "' ";
SqlCommand showresult = new SqlCommand(result, conn);
conn.Open();
showresult.ExecuteNonQuery();
string actresult = ((string)showresult.ExecuteScalar());
ResultLabel.Text = actresult;
conn.Close();
Need help please. Thanks!
Try this one.
string result = "SELECT ACTIVE FROM [dbo].[test] WHERE ID = '" + ID.Text + "' ";
SqlCommand showresult = new SqlCommand(result, conn);
conn.Open();
ResultLabel.Text = showresult.ExecuteScalar().ToString();
conn.Close();
Is there a typo in there? You have two calls to the database:
showresult.ExecuteNonQuery();
This won't return a value and I'm not sure why you would have it there
string actresult = ((string)shresult.ExecuteScalar());
Unless you have a shresult variable, this query should error. What is the shresult variable?
Use SqlParameter to filter the result and call ExecuteScalar() or ExecuteReader() method.
string result = "SELECT ACTIVE FROM [dbo].[test] WHERE ID=#ID";
SqlCommand showresult = new SqlCommand(result, conn);
// If ID is int type
showresult.Parameters.Add("#ID",SqlDbType.Int).Value=ID.Txt;
// If ID is Varchar then
//showresult.Parameters.Add("#ID",SqlDbType.VarChar,10).Value=ID.Txt;
conn.Open();
string actresult = (string)showresult.ExecuteScalar();
conn.Close();
if(!string.IsNullOrEmpty(actresult))
ResultLabel.Text = actresult;
else
ResultLabel.Text="Not found";
using (SqlConnection conn = new SqlConnection(connectionString))
{
string result = "SELECT ACTIVE FROM [dbo].[test] WHERE ID = #id";
SqlCommand showresult = new SqlCommand(result, conn);
showresult.Parameters.AddWithValue("id", ID.Text);
conn.Open();
ResultLabel.Text = showresult.ExecuteScalar().ToString();
conn.Close();
}
This will dispose the connection and has no string concatenation in the query.
conn.Open();
string result = "SELECT ACTIVE FROM test WHERE ID = '" + ID.Text + "' ";
SqlCommand showresult = new SqlCommand(result, conn);
showresult.ExecuteNonQuery();
int actresult = ((int)showresult.ExecuteScalar());
ResultLabel.Text = actresult.Tostring();
conn.Close();

Categories

Resources