I was wondering how could I retrieve the data from SQL server compact database that I just saved and insert it into textbox of newly created form. The source code is not complete, I just wanted to save space. Connection is fine, and I'm able to add data into database in the actual program. I just would like to know how to retrieve it and put it into textbox of newly created form. This is done in WinForms.Thank you!
public void b1_Click(object sender, EventArgs e)
{
SqlCeCommand command = new SqlCeCommand("INSERT INTO tbl1(Name) VALUES (#Name, #LastName)", conn);
command.Parameters.AddWithValue("#Name", t1.Text);
command.ExecuteNonQuery();
}
private void b2_Click(object sender, EventArgs e)
{
Form form2 = new Form();
form2.Show();
t3.Location = new System.Drawing.Point(0, 35);
t3.Size = new System.Drawing.Size(85, 15);
//access database and insert data into textbox
t3.Text = ?
form2.Controls.Add(t3);
}
Well it's not to hard to just get a value from the database, something like this should suit your needs:
SqlCeCommand command = new SqlCeCommand("SELECT * FROM tbl1(Name) WHERE name = #Name AND last_name = #LastName", conn);
command.Parameters.AddWithValue("#Name", "Hank");
command.Parameters.AddWithValue("#Name", "Hill");
SqlDataReader reader = command.ExecuteReader();
t1.Text = reader.GetString(0);
t2.Text = reader.GetString(1);
When in doubt, start at the official docs. See this sample, on msdn: http://msdn.microsoft.com/en-us/library/aa226134(v=sql.80).aspx
They show there a couple of SQL commands like SELECT, INSERT and UPDATE. You know how to insert, so you are now interested in the SELECT part. See how they use data reader and try that for starters.
Here is an example:
http://msdn.microsoft.com/en-us/library/aa983340(v=VS.80).aspx
Please also check codeplex.com for additional examples/projects
Related
I'm new to the database programming, so I have probably very simple question.
On the form I have a DataGridView which shows all records from the SQL database, from single table. When I select a line (OnRowEnter event), I would like to display the same data in the textBoxes, which are not binded to the DataSource, but I do not know how to access the selected record and its fields.
I have seen many examples which use SQL statements, but is it the only way? Or is there a simpler method. I thought I should be able to access the current record and its fields almost directly? Is it possible?
I'm using Visual Studio Community 2013
Thx in advance for your help.
private void dataGridView1_RowEnter(object sender, DataGridViewCellEventArgs e)
{
string asd = dataGridView1.Rows[e.RowIndex].Cells["NameOfColumn"].Value.ToString();
}
You can access any column of any row by this line.
EDIT:
You just told me you want to populate 2 textboxes from database and on buttons(save - overwrite) you want to save/overwrite it. So why you do not populate it from database
using (FbConnection con = new FbConnection(connectionString))
{
con.Open();
using (FbCommand cmd = new FbCommand("SELECT TEXT1, TEXT2 FROM TABLE WHERE CONDITION", con))
{
FbDataReader dr = cmd.ExecuteReader();
if(dr.Read())
{
textBox1.Text = dr[0].ToString();
textBox2.Text = dr[1].ToString();
}
}
con.close();
}
and then after user press save you just take whole text and update database
using (FbConnection con = new FbConnection(connectionString))
{
con.Open();
using (FbCommand cmd = new FbCoimmand("UPDATE TABLE SET TEXT1 = #Text1, TEXT2 = #Text2 WHERE CONDITION))
{
cmd.Parameters.AddWithValue("#Text1", textBox1.Text);
cmd.Parameters.AddWithValue("#Text2", textBox2.Text);
cmd.ExecuteNonQuery();
}
con.Close();
}
if user is writing text in some other textbox and you want to add that text to current text in database so you just read text from database and put it in string, on that string you add string from user and save like that to database
Background information:
I have a SQL connected datalist, one of the columns is called work_order
In the datalist I have inserted a button btn_Start. The button is populated at the end of each set
The goal of the btn_Start is to do a database insert, the insert needs to includes the work_order value from the set of data the button is clicked in (so the insert can be tied to the work_order value.)
btn_Start code:
protected void btn_Start(object sender, EventArgs e)
{
using (SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["nothanks"].ConnectionString))
{
String query = "INSERT INTO [TimeTest] ([Starttime], [Work_Order]) VALUES (#Starttime, #Work_Order)";
using (SqlCommand CCC = new SqlCommand(query, connection))
{
connection.Open();
CCC.CommandType = CommandType.Text;
CCC.Parameters.Add("#Starttime", SqlDbType.DateTime).Value = DateTime.Now;
CCC.Parameters.Add("#Work_Order", SqlDbType.Int).Value = lb_User1.Text.ToString();
CCC.ExecuteNonQuery();
}
}
}
To grab text of the work_order column, I'm using the itemcommand event to propagate a label (lb_User1).
DataList1_ItemCommand` code:
protected void DataList1_ItemCommand(object source, DataListCommandEventArgs e)
{
DataList2.SelectedIndex = e.Item.ItemIndex;
lb_User1.Text = (DataList2.SelectedItem.FindControl("Work_OrderLabel4") as Label).Text;
}
This works well, each time btn_Start is pushed, lb_User1 is updated with the right information.
The issue: when btn_Start is clicked, both btn_Start and DataList1_ItemCommand fire. But DataList1_ItemCommand fires after btn_Start. Which means lb_User1 isn't updated with the right info yet, and as such the insert fails to work as needed.
NOTES:
the lb_User1 isn't needed, I planned to go direct to the SQL insert. lb_User1 was used for code testing (so I can see what's going on)
My objective is to do the SQL insert with the grabbed data from datalist (Work_OrderLabel4). If I can accomplish this objective a better way that would also solve the issue.
btn_Start isn't going to be the only button in the datalist. One possible solution is go way from having two events and only doing things under the itemcommand event, but how do you separate out which button fires, without involving their respective events.
Objective: I'm trying to get each embedded start button to grab its corresponding work_order value for use in a SQL insert. The above is trying to accomplish this task, I'm almost there but I'm having the issue stated above. I'm open for other ways to accomplish this task (see picture of clarification)
Additional Information:
protected void DL_Main_ItemCommand(object source, DataListCommandEventArgs e)
{
using (SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["test"].ConnectionString))
{
String query = "INSERT INTO [TimeTest] ([Starttime], [Work_Order]) VALUES (#Starttime, #Work_Order)";
using (SqlCommand CCC = new SqlCommand(query, connection))
{
connection.Open();
CCC.CommandType = CommandType.Text;
CCC.Parameters.Add("#Starttime", SqlDbType.DateTime).Value = DateTime.Now;
// All you need is the value of Work_OrderLabel4 of the selected item so just do it like this.
CCC.Parameters.Add("#Work_Order", SqlDbType.Int).Value = (DL_Main.SelectedItem.FindControl("Work_OrderLabel") as Label).Text;
CCC.ExecuteNonQuery();
}
}
}
After Running
Get rid of btnStart and put the code below in your DataList1_ItemCommand. The only line I changed is the one with my comment:
using (SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["nothanks"].ConnectionString))
{
String query = "INSERT INTO [TimeTest] ([Starttime], [Work_Order]) VALUES (#Starttime, #Work_Order)";
using (SqlCommand CCC = new SqlCommand(query, connection))
{
connection.Open();
CCC.CommandType = CommandType.Text;
CCC.Parameters.Add("#Starttime", SqlDbType.DateTime).Value = DateTime.Now;
// All you need is the value of Work_OrderLabel4 of the selected item so just do it like this.
CCC.Parameters.Add("#Work_Order", SqlDbType.Int).Value = (DataList2.SelectedItem.FindControl("Work_OrderLabel4") as Label).Text;
}
CCC.ExecuteNonQuery();
}
}
Also, as a side note, please give your controls better names than DataList1. Perhaps DataListTimeTest since it deals with TimeTest table.
I am working in Visual Studio using C#. I need to get data from different database tables in SQL Server into text boxes on a Visual Studio form. The database tables have several rows and columns. The values are character and real values. I am using the code below. I don’t get the real values to text boxes. I get no errors and empty text boxes. I can get the character values. Can anyone please help? Thanks.
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
SqlConnection con = new SqlConnection("DataSource=192.146.1,5,1433;Network Library=DBMSSOCN;Initial Catalog=Estimator;User ID=id;Password=password;Trusted_Connection=True");
con.Open();
SqlCommand cmd = new SqlCommand("select * from Table1", con);
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
textBox1.Text = dr.GetString(1);
textBox2.Text = dr.GetString(2);
textBox2.Text = dr.GetString(3);
}
con.Close();
}
private void Form1_Load(object sender, EventArgs e)
{
}
}
}
Not sure why yours is not working but this similar post
How to display specific database entries into a textbox on a WinForm application
has several working examples.
You do have some odd stuff like datasource is spelled wrong and there are not enough digits in your IP address.
I don't know if SqlDataReader.GetString() will implicitly accept real data types.
But, nonetheless, I'd modify your while like this:
while (dr.Read())
{
var c1 = dr.Item[0];
var c2 = dr.Item[1];
var c3 = dr.Item[2];
textBox1.Text = dr.GetString(1);
textBox2.Text = dr.GetString(2);
textBox2.Text = dr.GetString(3);
}
This way you can see if there's anything actually coming out of you SqlDataReader. I'd only do this to help with the debugging process.
I'm stuck with something and I'd appreciate it if anyone can assist me.
I have a simple MS Access database that's linked to my program. The first thing I did was fill a combobox with one of the fields in my database ("Product Description").
What I'd like to do is when a user selects an item in the combobox, all the other fields in the record be displayed in text boxes.
string sConnection;
sConnection = "Provider=Microsoft.ACE.OLEDB.12.0;" +
"Data Source=XYZDatabase.accdb";
OleDbConnection dbConn;
dbConn = new OleDbConnection(sConnection);
dbConn.Open();
cbxProducts.DisplayMember = "Product Description";
dbConn.Close();
I've considered using possibly SQL or a DataReader, though I'm really not sure.
This is the event where I want the textboxes to be filled. I'm literally stuck here.
private void cbxProducts_SelectedIndexChanged(object sender, EventArgs e)
{
txtProductNumber.Text =
txtProductDescription.Text =
txtProductCategory.Text =
txtProductCost.Text =
}
I hope I haven't formatted my question wrong or anything, apologies if I have, this is my first time posting here! Dx
I wonder if your combo box is actually showing data from the DB.
In the first code block after
dbConn.Open()
and before
dbConn.Close()
you should have code like this:
SqlCommand sc = new SqlCommand("select prodid, proddesc from products", conn);
SqlDataReader reader;
reader = sc.ExecuteReader();
DataTable dt = new DataTable();
dt.Columns.Add("prodid", typeof(string));
dt.Columns.Add("proddesc", typeof(string));
dt.Load(reader);
cbxProducts.ValueMember = "prodid";
cbxProducts.DisplayMember = "proddesc";
cbxProducts.DataSource = dt;
And then in the second code block you need to fetch the selected Product ID first.
private void cbxProducts_SelectedIndexChanged(object sender, EventArgs e)
{
string ID = comboBox1.SelectedValue.ToString();
//Based on ID make a sql query and fetch the details of that product from the DB.
//Follow the earlier code block to make DB connection and execute query.
//Then populate the data in individual text boxes by looping through the dr.
//I am leaving this deliberately for you to figure out and I am sure you can.
txtProductNumber.Text =
txtProductDescription.Text =
txtProductCategory.Text =
txtProductCost.Text =
}
I am using ASP.NET 4.5 C#
I have a FormView in Insert mode, linked to an MSSQL database, with 2 hidden fields in it.
These fields are populated when the page loads.
I now need this data to be inputted to the database automatically without anyone having to click on an insert button.
How do I achieve this once the data has bound?
Here is the code I have been trying, it's working except the adnumber value is not uploading, only the date
protected void FormView1_DataBound(object sender, EventArgs e)
{
string ad, insertqry;
ad = ((HiddenField)(FormView1.FindControl("Adnumber"))).Value;
DateTime hit = DateTime.Now;
insertqry = "insert AdvertsHits(ad,hit) values(#ad,#hit)";
if (con.State == ConnectionState.Closed)
{
con.Open();
}
SqlCommand cmd = new SqlCommand(insertqry, con);
cmd.Parameters.Add("#ad", SqlDbType.VarChar, 250).Value = ad;
cmd.Parameters.Add("#hit", SqlDbType.DateTime).Value = hit;
cmd.ExecuteNonQuery();
cmd.Dispose();
con.Close();
}
Write a method to insert data into data base and call that method after hidden fields get the data, then data automatically inserted into database.