I am trying to make an app that stores some text, so I would like to use database connection (File I/O is discouraged)? And, How do i learn that and where to learn from? I don't know how to start, what to start and all, I have made GUI and want to make it working!
You could refer to the following code to insert some information from textbox to database.
private: System::Void button1_Click(System::Object^ sender, System::EventArgs^ e) {
String^ connstr = "connstr";
SqlConnection^ connection = gcnew SqlConnection(connstr);
connection->Open();
String^ sql = "Insert into Employee(ID,Name,Address)values(@ID,@Name,@Address)";
SqlCommand^ command = gcnew SqlCommand(sql, connection);
command->Parameters->AddWithValue("@ID", txtID->Text);
command->Parameters->AddWithValue("@Name",txtName->Text);
command->Parameters->AddWithValue("@Address", txtAddress->Text);
command->ExecuteNonQuery();
connection->Close();
MessageBox::Show("success");
}
private: System::Void button2_Click(System::Object^ sender, System::EventArgs^ e) {
dataGridView1->DataSource = 0;
String^ connstr = "connstr";
SqlConnection^ connection = gcnew SqlConnection(connstr);
connection->Open();
String^ sql = "Select * from Employee";
//SqlCommand^ command = gcnew SqlCommand(sql, connection);
SqlDataAdapter^ adapter = gcnew SqlDataAdapter(sql, connection);
DataTable^ table = gcnew DataTable();
adapter->Fill(table);
dataGridView1->DataSource = table;
connection->Close();
}
Note:Button1_click is used to insert data to database. Button2_click is used to show data from database in the datagridview. Please use \\
to replace \
in the connectionstring.
Result: