【发布时间】:2021-03-15 08:10:09
【问题描述】:
我的问题看起来很琐碎,但不幸的是我不知道如何解决这个问题。
一个数据库中有一个表。我必须通过单击该表的按钮来添加数据。当用户单击按钮时,他/她将进入某种形式,他/她可以在其中输入数据。第一次最好能输入:id、服务种类、价格。我决定创建一个新类,我将在其中包含所有变量,包括这三个变量。这些变量是公开的。
我还决定从文本框中读取文本并将此信息写入该类的变量中。在第二种形式中,有 2 个按钮。 “确定”和“取消”。我决定使用 ShowDialog。
我能够将表从数据库输出到 DataGridView,但我不太清楚如何将数据添加到我的表中并在插入后在 datagridview 中成功展示。
我的班级:
public class AllDataDB
{
public int id_serv;
public double price;
public string name;
}
第二种形式:
public partial class TypeService : Form
{
public AllDataDB Class;
public TypeService(AllDataDB t)
{
Class = t;
InitializeComponent();
}
private void button2_Click(object sender, EventArgs e)
{
this.Close();
}
private void button1_Click(object sender, EventArgs e)
{
AllDataDB Class = new AllDataDB();
Class.id_serv = Convert.ToInt32(textBox3.Text);
Class.name = NameService.Text;
Class.price = Convert.ToDouble(PriceService.Text);
this.DialogResult = DialogResult.OK;
this.Close();
}
}
按钮调用表单和查询的工作:
private void NewServe_Click(object sender, EventArgs e)
{
AllDataDB Class = new AllDataDB();
TypeService form = new TypeService(Class);
if (form.ShowDialog() == DialogResult.OK)
{ // відповідно до класу створюється новий запис. INSERT.
SqlConnection Con = new SqlConnection(connectionString);
Con.Open();
string Que = "INSERT INTO type_service " +
"VALUES(" + Class.id_serv + " ,'" + Class.name +
"' ," + Class.price + " );" +
"SELECT * FROM type_service";
SqlCommand cmd = new SqlCommand(Que, Con);
cmd.ExecuteNonQuery();
Con.Close();
SqlDataAdapter sqlDa = new SqlDataAdapter("SELECT * FROM type_service", Con);
DataTable d = new DataTable();
sqlDa.Fill(d);
dataGridView3.AutoGenerateColumns = false;
dataGridView3.DataSource = d;
}
}
【问题讨论】:
标签: c# sql sql-insert showdialog