I have a form with ComboBox to list items name and label PRODUCTID Value to describe its item ID:
I have a class Connect to query. Here is the code:
class Connect
{
SqlConnection con;
public Connect()
{
String connectionString = #"Data Source=.\SQLEXPRESS;AttachDbFilename=" + Application.StartupPath + #"\Database1.mdf;Integrated Security=True;User Instance=True";
con = new SqlConnection(connectionString);
}
public DataTable executeSelect(String query)
{
con.Open();
SqlDataAdapter adapter = new SqlDataAdapter(query, con);
DataTable dt = new DataTable();
adapter.Fill(dt);
con.Close();
return dt;
}
public void execute(String query)
{
con.Open();
SqlCommand cmd = new SqlCommand(query, con);
cmd.ExecuteNonQuery();
con.Close();
}
}
My problems is I want my form to show its Product ID when i choose selected item in comboBox. And the data is the same with the data in database For example, I select Batman book in combo box, the label will show its Product ID and the ID must be the same in database. Could you please give me the example of code to solve this problem?? Thank you
private void cboType_SelectedIndexChanged(object sender, EventArgs e)
{
string ptype = cboType.Text.ToString().Trim();
//change query according to your db
string sql = string.Format(#"select productid from yourtable where producttype = '{0}'", ptype);
Connect con = new Connect();//you should learn ExecuteScalar method
DataTable dt = con.executeSelect(sql);
object id = dt.Rows[0][0];//assume data in db is consistent,
this.lblID.Text = id.ToString();
}
Related
Hello all I am trying to populate some textboxes automatically when I select an item from a combobox dropdown list using Microsoft sql server with a usercontrol form. I have written the codes below, however I am getting the items in the combox dropdown list but when I select an item in the combobox dropdown list, nothing happens in the text boxes. the values are in a table called competitors. the columns are Institution, Region, FirstName, LastName and I want the values to display in the respective textboxes when I select the combox dropdown. I seek your assistance in solving this problem. thanks in advance
private void RabbitCare_Load(object sender, EventArgs e)
{
CBoxParishDdlist.Items.Clear();
SqlConnection connect = new SqlConnection(#"Data Source=ITSPECIALIST\SQLPROJECTS;Initial Catalog=EXPRORESULTS;Integrated Security=True ");
connect.Open();
SqlCommand cmd = connect.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "Select ParishName FROM Competitors WHERE CompetitiveEventName = 'Care and Management of Bees'";
cmd.ExecuteNonQuery();
DataTable dat = new DataTable();
SqlDataAdapter SDA = new SqlDataAdapter(cmd);
SDA.Fill(dat);
foreach (DataRow DAR in dat.Rows)
{
CBoxParishDdlist.Items.Add(DAR["ParishName"].ToString());
}
connect.Close();
}
private void CBoxParishDdlist_SelectedIndexChanged(object sender, EventArgs e)
{
SqlConnection connect = new SqlConnection(#"Data Source=ITSPECIALIST\SQLPROJECTS;Initial Catalog=EXPRORESULTS;Integrated Security=True ");
connect.Open();
cmd = new SqlCommand("SELECT * FROM Competitors WHERE ParishName = '" + CBoxParishDdlist.Text + "'", connect);
cmd.ExecuteNonQuery();
SqlDataReader dr;
dr = cmd.ExecuteReader();
while (dr.Read())
{
string Institution = (string)dr["Institution"].ToString();
TxtBoxInstitution.Text = Institution;
string Region = (string)dr["Region"].ToString();
TxtBoxRegion.Text = Region;
string FirstName = (string)dr["FirstName"].ToString();
TxtBoxFname.Text = FirstName;
string LastName = (string)dr["LastName"].ToString();
TxtBoxLname.Text = LastName;
}
connect.Close();
I think this will solve your problem.
TxtBoxInstitution.Text = comboBoxName.SelectedItem.ToString();
Now this may be a "Noob" question. But I cant seem to do any commands that people seem to do with The DataGrid. What is the difference, and why can I only get DataGrid?
My problem is that I am trying to delete rows in the datagrid when they are pulled from a database. But, I cant figure out how because the SelectRows command does not work.
That is what i have so far. Is there anyway i can get DataGrid?
EDIT:
This is how I get information into the datagrid.
private void Button_Click(object sender, RoutedEventArgs e)
{
foreach (DataGridViewRow row in userDataGrid.SelectedRows)
{
if (!row.IsNewRow)
dataGridView1.Rows.Remove(row);
}
}
SqlConnection conn = new SqlConnection();
conn.ConnectionString = "Server=----; Database=----; User id=vsd; password=----";
conn.Open();
dt = new DataTable();
sda = new SqlDataAdapter("SELECT TeacherID, ClassName, ClassID FROM CLASS", conn);
sda.Fill(dt);
userDataGrid.ItemsSource = dt.DefaultView;
conn.Close();
Also, If there is a better way to do this, please let me know as well. I am very new to all of this.
Use the same instance of DataTable every time when you pull rows from db.
DataTable mDataTable = new DataTable(); //class field
public Constructor()
{
InitializeComponent();
userDataGrid.ItemsSource = mDataTable .mDataTable;
}
void PullData()
{
mDataTable.Clear();
using (SqlConnection conn = new SqlConnection(ConnectionString))
{
conn.Open();
sda = new SqlDataAdapter("SELECT TeacherID, ClassName, ClassID FROM CLASS", conn);
sda.Fill(mDataTable );
}
}
It should solve your problem, but it's bad approach.
As Bizz adviced look at MVVM pattern & entity framework.
This is what I ended up doing for deleting the button. Most answers were trying to answer to a DataGridView. But, This is not WinForms or a DataGridView. This is WPF and its just DataGrid.
This is what I did to delete the row from the grid and the database.
private void delete_Click(object sender, RoutedEventArgs e)
{
DataGrid dg = this.aSSIGNMENTDataGrid;
var id1 = (DataRowView)dg.SelectedItem; //Get specific ID From DataGrid after click on Delete Button.
PK_ID = Convert.ToInt32(id1.Row["AssignmentID"].ToString());
SqlConnection conn = new SqlConnection(sqlstring);
conn.Open();
string sqlquery = "delete from ASSIGNMENT where AssignmentID='" + PK_ID + "' ";
SqlCommand cmd = new SqlCommand(sqlquery, conn);
cmd.ExecuteNonQuery();
filldatagrid();
}
private void filldatagrid()
{
SqlConnection conn = new SqlConnection(sqlstring);
conn.Open();
string sqlquery = "select * from ASSIGNMENT";
SqlCommand cmd = new SqlCommand(sqlquery, conn);
SqlDataAdapter adp = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
adp.Fill(dt);
aSSIGNMENTDataGrid.ItemsSource = dt.DefaultView;
conn.Close();
}
private void fillProduct() {
SqlConnection conn = new SqlConnection("Data Source=STATION21\\SQLEXPRESS;Initial Catalog=mydb;Integrated Security=true");
conn.Open();
string query = "Select prodID from product";
SqlCommand cmd = new SqlCommand(query, conn);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
if (dt.Rows.Count > 0) {
cmbPCode.DataSource = dt;
cmbPCode.DisplayMember = "prodID";
cmbPCode.ValueMember = "prodID";
}
private void cmbPCode_SelectedIndexChanged(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection("Data Source=STATION21\\SQLEXPRESS;Initial Catalog=mydb;Integrated Security=true");
con.Open();
string query = "Select * from product where prodID = '"+cmbPCode.Text+"'".ToString();
SqlCommand cmd = new SqlCommand(query, con);
SqlDataReader dr = cmd.ExecuteReader();
if (dr.Read()) {
tbdc.Text = dr["prodDescription"].ToString();
}
}
i am having trouble with getting my items from the database according to the selected index i get this error
Conversion failed when converting the varchar value
'System.Data.DataRowView' to data type int
can someone please help me how to convert SqlDataReader to String. because i notice that when i retrieve a column with varchar/string datatype i am not having this kind error but if i retrieve a column with int datatype i get this error.
Replace This:
string query = "Select * from product where prodID = '"+cmbPCode.Text+
"'".ToString();
With This:
string query = "Select * from product where prodID = "+cmbPCode.Text;
Suggestion: Your query is open to SQL Injection i would suggest you to use parameterised queries to avoid them.
Using Parameterised Queries:
string query = "Select * from product where prodID = #ID";
SqlCommand cmd = new SqlCommand(query, con);
cmd.Parameters.AddWithValue("#ID",cmbPCode.Text);
private void Form1_Load(object sender, EventArgs e)
{
string Sql = "select project_name from tb_project";
OleDbConnection con = new OleDbConnection(constr);
OleDbCommand com = new OleDbCommand(Sql, con);
con.Open();
OleDbDataReader DR = com.ExecuteReader();
while (DR.Read())
{
combo_status.Items.Add(DR[0]);
}
con.Close();
}
in this code i am fetching project name from a table in database and showing them in combobox but what i want is that in this is that in the table from where i am fetching project name there is a project id corresponding to that name...so i want project name to be displayed in combox and when i click on submit then it should insert project id corresponding to the project name choosen in combobox so how can i do that.....
Try this :
string Sql = "select project_name, project_id from tb_project";
con = new OleDbConnection(constr);
com = new OleDbCommand(Sql, con);
con.Open();
OleDbDataReader DR = com.ExecuteReader();
DataTable table = new DataTable();
table.Load(dr);
combo_status.DataSource = table;
combo_status.DisplayMember = "project_name";
combo_status.ValueMember= "project_id";
As per my understanding, you want to insert the project id of the selected project name in some other table. To accomplish this you can use following code:
private void Form1_Load(object sender, EventArgs e)
{
string Sql = "select project_id, project_name from tb_project";
OleDbConnection con = new OleDbConnection(constr);
OleDbCommand com = new OleDbCommand(Sql, con);
con.Open();
DataSet ds = new DataSet();
OleDbDataAdapter da = new OleDbDataAdapter(com);
da.Fill(ds);
combo_status.DataSource = ds.Tables[0];
combo_status.DisplayMember = "project_name";
combo_status.ValueMember = "project_id";
com.Dispose();
con.Close();
}
In this way you will find the project name using combo_status.SelectedText and you will find the project id using combo_status.SelectedValue. Now you can use it anywhere you want.
Use DisplayMember and ValueMember Of Combobox
// Fetch Both Project Name and Project Id
string Sql = "select project_name, project_id from tb_project";
con = new OleDbConnection(constr);
com = new OleDbCommand(Sql, con);
con.Open();
OleDbDataReader DR = com.ExecuteReader();
DataTable dt;
dt.Load(Dr);
combo_status.DataSource = dt; //Check it this works or not
combo_status.DisplayMember = "project_name";
combo_status.ValueMember= "project_id";
To get Project_id of Selected project_name
Int64 varproject_Id = Convert.ToInt64(combo_status.SelectedValue);
try this
while (DR.Read())
{
combo_status.Items.Add(DR.GetValues(0).toString());
}
Still learning C#
A comboBox is created and Tables called mainCat and subCat is created.
I have a code , but i am stuck to understand on how to get the data from mainCat to the comboBox , which is then used by another comboBox for the subCat to set a subcategory.
The Get Connection is underlined red. Why?
Here is my code -
System.Data.SqlServerCe.SqlCeConnection con;
System.Data.SqlServerCe.SqlCeDataAdapter da;
DataSet ds1;
private void Form2_Load(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection();
conn.ConnectionString = "Data Source=.\\SQLEXPRESS;Initial Catalog=master;Integrated Security=True";
conn.Open();
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
using (SqlConnection Con = GetConnection())
{
SqlDataAdapter da = new SqlDataAdapter("Select Category.Category ,Category.Id from Category", Con);
SqlCommand cmd = new SqlCommand("SELECT * from MAINCAT");
DataTable dt = new DataTable();
da.Fill(dt);
mainCatU.DataSource = dt;
mainCatU.DisplayMember = "Category";
mainCatU.ValueMember = "Id";
mainCatU.Text = "<-Please select Category->";
myComboBox.DropDownStyle = ComboBoxStyle.DropDownList;
}
}
So i then i tried another code.. but still doesnt work..
public partial class User : Form
{
System.Data.SqlServerCe.SqlCeConnection con;
System.Data.SqlServerCe.SqlCeDataAdapter da;
DataSet ds1;
private void User_Load(object sender, EventArgs e)
{
con = new System.Data.SqlServerCe.SqlCeConnection();
con.ConnectionString = "Data Source=PEWPEWDIEPIE\\SQLEXPRESS;Integrated Security=True";
con.Open();
MessageBox.Show("Database connected");
ds1 = new DataSet();
string sql = "SELECT * from MAINCAT";
da = new System.Data.SqlServerCe.SqlCeDataAdapter(sql, con);
da.Fill(ds1, "SCSID");
mainCatU.DataSource = ds1;
con.Close();
mainCatU.Text = "<-Please select Category->";
mainCatU.DropDownStyle = ComboBoxStyle.DropDownList;
mainCatU.Enabled = true;
}
}
then i just used the data bound item function through the combobox GUI..
this.mAINCATTableAdapter.Fill(this.masterDataSet.MAINCAT);
but , the box didn't show any value , except "System.Data.DataRowView" in the comboBox
==================================================================================
System.Data.SqlServerCe.SqlCeConnection con; //not used at the moment
System.Data.SqlServerCe.SqlCeDataAdapter da; //not used at the moment
DataSet ds1;
private void User_Load(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection();
conn.ConnectionString = "Data Source=PEWPEWDIEPIE\\SQLEXPRESS;Initial Catalog=master;Integrated Security=True";
conn.Open();
MessageBox.Show("Database connected");
SqlDataAdapter da = new SqlDataAdapter("SELECT * from MAINCAT", conn);
ds1 = new DataSet();
da.Fill(ds1, "MainCat");
mainCatU.DisplayMember = "maincat";
mainCatU.ValueMember = "maincat";
mainCatU.DataSource = ds1.Tables["MAINCAT"];
}
===============
and the combo box is still not showing anything from the database table
You need to create the function GetConnection():
public string ConnectionString { get; set;}
public SqlConnection GetConnection()
{
SqlConnection cn = new SqlConnection(ConnectionString);
return cn;
}
TBH, unless you want to do something in GetConnection, you might be better just creating it inline:
using (SqlConnection Con = new SqlConnection(ConnectionString))
{
EDIT:
Based on your revised question, I think the problem now may be here:
mainCatU.DisplayMember = "maincat";
mainCatU.ValueMember = "maincat";
mainCatU.DataSource = ds1.Tables["MAINCAT"];
My guess is that your table structure is not maincat.maincat. The display and value members should be set to the field name that you wish to display.
I am really sorry I am a vb developer but the concept is same to populate data into combo using sql is
Declare SQLConnection Declare SQLDataReader Declare SQLCommand
Try
If Con.State = ConnectionState.Closed Then
Con.Open()
cmd.Connection = Con
cmd.CommandText = "Select field1, field2 from table"
dr = cmd.ExecuteReader()
' Fill a combo box with the datareader
Do While dr.Read = True
ComboBoxName.Items.Add(dr.GetString(0))
ComboBoxName.Items.Add(dr.GetString(1))
Loop
Con.Close()
End If
Catch ex As Exception
MsgBox(ex.Message)
End Try
Hope it works for you.