سلام
استفاده مستقیم از متدها یا مثلا همین کانکشن استرینگ تو تمرین مشکلی نیست اما تو پروژه هایی که قرار کار ازش کشیده بشه بهتره توی یه کلاس گذاشته بشه و متدهای کنترل کانکشن هم باشه
همون کدهای شماست یه تغییر جزیی دادم
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data;
using System.Data.SqlClient;
using System.Windows.Forms;
namespace InsertingRecordConnected
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private static string connection = @"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename="+Application.StartupPath+@"\university30.mdf;Integrated Security=True;Connect Timeout=30";
private void button1_Click(object sender, EventArgs e)
{
SqlConnection cnn = new SqlConnection(connection);
SqlCommand command = new SqlCommand("INSERT INTO students30 (firstname,lastname,gender,age,address)Values(@firstname,@lastname,@gendder,@age,@address)",cnn);
command.Parameters.Clear();
command.Parameters.AddWithValue("@firstname", firstnametextbox.Text);
command.Parameters.AddWithValue("@lastname", lastnametextbox.Text);
command.Parameters.AddWithValue("@gender", gendertextbox.Text);
command.Parameters.AddWithValue("@age", agetextbox.Text);
command.Parameters.AddWithValue("@address", addresstextbox.Text);
cnn.Open();
int result = command.ExecuteNonQuery();
cnn.Close();
if (result > 0)
{
MessageBox.Show("Student succesfully added");
//refreshdatabasemethod
//txtclear-method
}
else
MessageBox.Show("Failed to add student");
}
}
}
}