I would like to retrieve a particular column from a table when the values from two other columns are equal. My code is as follows. The four columns are id,destination,source,price.
I want to display the price when the destination and source are equal.
Could you please help me?
private void button1_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection("Data source=.;initial catalog=loki;integrated security=true");
con.Open();
SqlDataAdapter da = new SqlDataAdapter();
DataTable dt = new DataTable();
da.SelectCommand = new SqlCommand("select price from metro where source='" + textBox1.Text + "' and destination='" + textBox2.Text + "'", con);
da.Fill(dt);
for(int i=0;i<dt.Rows.Count;i++)
{
textBox3.Text = dt.Rows[0][3].Count.ToString();
}
}
I thing you are after this ....
private void button1_Click(object sender, EventArgs e)
{
using (SqlConnection con = new SqlConnection("Data source=.;initial catalog=loki;integrated security=true"))
{
string query = "select price from metro where source= #Source and destination = #Destination";
using (SqlCommand cmd = new SqlCommand(query, con))
{
cmd.Parameters.AddWithValue("#Source", textBox1.Text);
cmd.Parameters.AddWithValue("#Destination", textBox2.Text);
con.Open();
object o = cmd.ExecuteScalar();
if(o != null && o != DBNull.Value)
{
string price = (string) o; //please cast the return type as required
textBox3.Text = price;
}
con.Close();
}
}
}
Related
Whenever I tried to get the value from treeview in which I get the data from database on Get Data button and try to display it on datagridview by checking the checkbox of treeview node it will not display the details of that node in datagridview on Search button.
Treeview after getting the data from Database on Get Data Button:
So, I want now is that whenever I check the treeview node and then click on Search button it must show all details of that node in datagridview.
My Code of this Winform:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace My_Work
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Get_Data_Click(object sender, EventArgs e)
{
string conStr = "Integrated Security=SSPI;Persist Security Info=False;Initial Catalog=Data;Data Source=MY-PC";
SqlConnection con = new SqlConnection(conStr);
con.Open();
string query = "select ItemNo,UnitePrice from Product_Item";
SqlCommand cmd = new SqlCommand(query, con);
SqlDataReader sdr = cmd.ExecuteReader();
while (sdr.Read())
{
TreeNode n = new TreeNode(sdr["ItemNo"].ToString());
treeView1.Nodes.Add(n);
n.Nodes.Add(sdr["UnitePrice"].ToString());
}
con.Close();
}
private void treeView1_NodeMouseClick(object sender, TreeNodeMouseClickEventArgs e)
{
string conStr = "Integrated Security=SSPI;Persist Security Info=False;Initial Catalog=Data;Data Source=MY-PC";
SqlConnection con = new SqlConnection(conStr);
con.Open();
string nodeName = e.Node.ToString().Replace("TreeNode: ", string.Empty);
if (e.Node.Parent != null)
{
string q = "select * from Product_Item where UnitePrice='" + nodeName + "'";
SqlCommand cmd = new SqlCommand(q, con);
SqlDataAdapter sda = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
sda.Fill(dt);
con.Close();
dataGridView1.DataSource = dt;
}
}
private void Search_Click(object sender, EventArgs e)
{
string conStr = "Integrated Security=SSPI;Persist Security Info=False;Initial Catalog=Data;Data Source=MY-PC";
SqlConnection con = new SqlConnection(conStr);
con.Open();
if(treeView1.CheckBoxes == true)
{
string nodeCheck = treeView1.CheckBoxes.ToString();
string q = "select * from Product_Item where ItemNo='" + nodeCheck + "'";
SqlCommand cmd = new SqlCommand(q, con);
SqlDataAdapter sda = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
sda.Fill(dt);
con.Close();
dataGridView1.DataSource = dt;
}
}
}
}
This is the code in which I want to get the details of check node but I cannot get the details of that node.
private void Search_Click(object sender, EventArgs e)
{
string conStr = "Integrated Security=SSPI;Persist Security Info=False;Initial Catalog=Data;Data Source=MY-PC";
SqlConnection con = new SqlConnection(conStr);
con.Open();
if(treeView1.CheckBoxes == true)
{
string nodeCheck = treeView1.CheckBoxes.ToString();
string q = "select * from Product_Item where ItemNo='" + nodeCheck + "'";
SqlCommand cmd = new SqlCommand(q, con);
SqlDataAdapter sda = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
sda.Fill(dt);
con.Close();
dataGridView1.DataSource = dt;
}
}
Database Table Product_Item:
The TreeView.CheckBoxes Property returns a Boolean telling you whether the treeview displays checkboxes. You cannot get the required SQL condition out of it, but you can get the item numbers of the checked items with
var itemNums = new List<string>();
foreach (TreeNode node in treeView1.Nodes)
{
if (node.Checked) {
itemNums.Add(node.Text);
}
}
Now, you must create a SQL condition from this list. Assuming that these numbers are stored in a int column, we can create a list of numbers with
string numList = String.Join(", ", itemNums);
and then use this to build the SQL statement:
string sql = "SELECT * FROM Product_Item WHERE ItemNo IN (" + numList + ")";
If, however, the item numbers are stored in a text column, then we must write
string numList = String.Join("', '", itemNums);
string sql = "SELECT * FROM Product_Item WHERE ItemNo IN ('" + numList + "')";
This produces conditions looking like WHERE ItemNo IN (1, 7, 9) or
WHERE ItemNo IN ('1', '7', '9').
I have a problem , i'm trying to do operations between values recorded(type float) in table of data , the problem is when i try to update value(result of the operation in textbox) in datable using combobox after maintaining opération , it shows me error (System.Data.SqlClient.SqlException: 'Error converting data type varchar to float.'), So how can i resolve that !help please
This is a part a of my code in which the error exists
private void comboBox5_SelectedIndexChanged(object sender, EventArgs e)
{
con.Open();
String query = "UPDATE Table_com SET Contents='" + textBox6.Text + "' WHERE Variable='" + comboBox5.Text + "'";
SqlDataAdapter SDA = new SqlDataAdapter(query, con);
SDA.SelectCommand.ExecuteNonQuery();
SqlCommand cmd = con.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "select * from Table_com where Variable='" + comboBox5.SelectedItem.ToString() + "'";
cmd.ExecuteNonQuery();
DataTable dt = new DataTable();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);
con.Close();
MessageBox.Show("Variable mise à jour avec succés");
}
You cannot use float integer etc. values like text field as:
String query = "UPDATE Table_com SET Contents='" + textBox6.Text + "' WHERE Variable='" + comboBox5.Text + "'";
and your code really risky, you may use parameters like this, dont use string and convert your value to float :
static void Main(string[] args)
{
var ConnectionString = "YOUR CONNECTION STRING";
DataTable dt = new DataTable();
using (SqlConnection con = new SqlConnection(ConnectionString))
{
String query = "UPDATE Table_com SET Contents=#contents WHERE Variable=#variable";
using (SqlCommand cmd = new SqlCommand(query, con))
{
cmd.CommandType = System.Data.CommandType.Text;
cmd.Parameters.Add("#contents", SqlDbType.Float).Value = Convert.ToDouble(textBox6.Text);
cmd.Parameters.Add("#variable", SqlDbType.NVarChar).Value = comboBox5.Text;
using (SqlDataAdapter da = new SqlDataAdapter(cmd))
{
da.Fill(dt);
}
}
}
}
this is what i tried refering to wikiCan answer
SqlConnection con = new SqlConnection(#"Data Source=DESKTOP-VEFPLGG\SQLEXPRESS;Initial Catalog=test;Integrated Security=True");
private void comboBox5_SelectedIndexChanged(object sender, EventArgs e)
{
DataTable dt = new DataTable();
String query = "UPDATE Table_com SET Contents=#contents ";
using (SqlCommand cmd = new SqlCommand(query, con))
{
cmd.CommandType = System.Data.CommandType.Text;
cmd.Parameters.Add("#contents", SqlDbType.Float).Value = textBox6.Text;
//cmd.Parameters.Add("#variable", SqlDbType.Float).Value = Convert.ToDouble(comboBox5.Text);
using (SqlDataAdapter da = new SqlDataAdapter(cmd))
{
da.Fill(dt);
}
}
}
I wanat to retrieve student ID from database. Here is my code what i have tried but it is not displaying anything.
Thanks...
protected void Button2_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection("Data Source=DESKTOP-Q69PRF4;Initial Catalog=new;Integrated Security=True");
if (con.State == ConnectionState.Open)
{
con.Close();
}
con.Open();
string str = "select * from StRecords where StID='" + Session["login"] + "'";
SqlCommand com = new SqlCommand(str, con);
SqlDataAdapter da = new SqlDataAdapter(com);
DataSet ds = new DataSet();
DataTable dt = new DataTable();
da.Fill(dt);
if (dt.Rows.Count > 0)
{
Label11.Text = dt.Rows[0]["StID"].ToString();
}
}
If you want to take just StudentId from the database, then you just select that column and use ExecuteScalar property.
Code
protected void Button2_Click(object sender, EventArgs e)
{
using (SqlConnection con = new SqlConnection("Data Source=DESKTOP-Q69PRF4;Initial Catalog=new;Integrated Security=True"))
{
con.Open();
string str = "select [StID] from StRecords where StID = #stdId;";
using (SqlCommand com = new SqlCommand(str, con))
{
com.Parameters.AddWithValue("#stdId", Session["login"]);
Label11.Text = com.ExecuteScalar().ToString();
}
}
}
Also always use parameters instead passing the value in single quotes to avoid SQL injection attack.
Also try to give the connection string in Web.Config file.
I keep on getting the Name instead of the Price.What I want is I pick a value on The DropdownList and Load its price on the label.
private void GetData()
{
SqlConnection connection = new SqlConnection("Data Source = localhost\\SQLEXPRESS;Initial Catalog = MejOnlineManagementDB00;Integrated Security=True;");
connection.Open();
SqlCommand sqlCmd = new SqlCommand(#"SELECT price
FROM Products3
WHERE productName='" + DropDownList1.SelectedItem.Value.ToString() + "'", connection);
SqlDataReader rdr = sqlCmd.ExecuteReader();
while (rdr.Read())
{
lblPrice.Text = DropDownList1.SelectedValue.ToString();
}
connection.Close();
}
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
lblPrice.Text=DropDownList1.SelectedItem.Value.ToString();
}
above is my selectedIndex.
Change your code into this:
private void GetData()
{
SqlConnection connection = new SqlConnection("Data Source = localhost\\SQLEXPRESS;Initial Catalog = MejOnlineManagementDB00;Integrated Security=True;");
connection.Open();
SqlCommand sqlCmd = new SqlCommand(#"SELECT price
FROM Products3
WHERE productName='" + DropDownList1.SelectedItem.Value.ToString() + "'", connection);
SqlDataReader rdr = sqlCmd.ExecuteReader();
if(dr.HasRows)
{
while (rdr.Read())
{
lblPrice.Text = rdr.GetValue(0).ToString(); // if price is string use GetString(0))
}
}
connection.Close();
}
EDIT:
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
GetData();
}
I have two tables in a SQL Server database. I select from table ADMS and I need to insert master table by gridview but I dont know how to insert with gridview. Please help. I've tried for many days and I did not pass yet
protected void Button3_Click1(object sender, EventArgs e)
{
if (RadioButton2.Checked)
{
SqlConnection con = new SqlConnection(MyConnectionString);
// con.Open(); // don't need the Open, the Fill will open and close the connection automatically
SqlDataAdapter da = new SqlDataAdapter("SELECT * FROM ADMS_Machining where datetime='" + TextBox1.Text + "'", con);
mytable = new DataTable();
da.Fill(mytable);
GridView2.DataSource = mytable;
GridView2.DataBind();
}
else
{
SqlConnection con = new SqlConnection(MyConnectionString);
// con.Open(); // don't need the Open, the Fill will open and close the connection automatically
SqlDataAdapter da = new SqlDataAdapter("SELECT * FROM Machining_Master where datetime='" + TextBox1.Text + "'", con);
mytable = new DataTable();
da.Fill(mytable);
GridView2.DataSource = mytable;
GridView2.DataBind();
}
}
protected void Button4_Click(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection();
SqlCommand cmd = new SqlCommand();
String strConnString, strSQL;
strConnString = "Server=kane-pc;UID=sa;PASSWORD=1234;Database=Machining;Max Pool Size=400;Connect Timeout=600;";
//here
conn.ConnectionString = conn;
conn.Open();
cmd.Connection = conn;
cmd.CommandText = strSQL;
}
You can extract values from a grid view depending on what you have placed in the cells...
string value = this.GridView2.Rows[0].Cells[0].Text;
You can also track the selected row event, and get specific controls like the following...
protected void OnSelectedIndexChanged(object sender, EventArgs e)
{
string someValueTakenFromLabel = (GridView2.SelectedRow.FindControl("lblAnyLabelHere") as Label).Text;
// .... do something with value here
}
I suggest you go through some tutorials though to get the hang of how to use GridView.
http://www.asp.net/web-forms/videos/building-20-applications/lesson-8-working-with-the-gridview-and-formview
http://www.aspsnippets.com/Articles/How-to-get-Selected-Row-cell-value-from-GridView-in-ASPNet.aspx
http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.gridview%28v=vs.110%29.aspx
You have to first read data from cells and then insert them into database using SqlCommand.
Assuming that you have M_ID and M_NAME columns in your Machining_Master table you can insert values to database as below:
//Assuming that your id column is first column and name is second column
//get value of id and name
int mId = Convert.ToInt32(GridView2.SelectedRow.Cells[0].Text);
string mName = GridView2.SelectedRow.Cells[1].Text;
string connectionStrng = "your connection string";
string insertSql = "INSERT INTO Machining_Master (M_ID, M_NAME) VALUES (#mId, #mName)";
using (SqlConnection conn = new SqlConnection(connectionStrng))
{
using (SqlCommand cmd = new SqlCommand(insertSql, conn))
{
try
{
cmd.Parameters.Add(new SqlParameter("mId", mId));
cmd.Parameters.Add(new SqlParameter("mName", mName));
conn.Open();
cmd.ExecuteNonQuery();
}
finally
{
//Close connection
conn.Close();
}
}
}