将Windows窗体绑定到sql服务器数据库 [英] binding a windows form to a sql server database

查看:67
本文介绍了将Windows窗体绑定到sql服务器数据库的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在将Windows窗体绑定到数据库时,我感到非常困惑.

基本上,我应该能够通过Windows窗体输入数据,并且应该在数据库中对其进行更新.

当输入特定的ID时,我也应该能够查看详细信息.

请帮忙

I am very confused when it comes to binding the windows form to a database.

Basically i should be able to input the data via the windows form and it should get updated in the database.

Also i should be able to view the details when a particular id is input.

PLease do help

using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;

namespace student_database
{
    public partial class Form1 : Form
    {
        private SqlConnection connection;
        private SqlCommand command;
         
        private SqlDataAdapter adapter;
        private SqlCommandBuilder builder;
        private DataSet dataset;
        private bool updateReady;
        private bool insertReady;

        public Form1()
        {
            InitializeComponent();
            textBox1.Focus();
            textBox2.Focus();
            textBox3.Focus();
            textBox4.Focus();
       
            connection = new SqlConnection();
            command = connection.CreateCommand();
            connection.ConnectionString=@"Data Source=(local)" +
                                        "Initial Catalog=student details;Integrated Security=SSPI";

            command = connection.CreateCommand();
            adapter = new SqlDataAdapter(command);
            builder = new SqlCommandBuilder(adapter);
            dataset = new DataSet(); 
        }

        private void button1_Click(object sender, EventArgs e)
        {
            command.Parameters.Clear();
            command.Parameters.AddWithValue("@StudentID", textBox1.Text);
            command.CommandText = "SELECT * FROM student details WHERE StudentID=@StudentID";
            

            dataset.Tables.Clear();

            int result = adapter.Fill(dataset, "student details");

            if (result > 0)
            {
                DataRow srow = dataset.Tables["student details"].Rows[0];
                textBox1.Text = srow["StudentID"].ToString();
                textBox2.Text = srow["Name"].ToString();
                textBox3.Text = srow["Age"].ToString();
                textBox4.Text = srow["CourseNo"].ToString();
            }
            else
            {
                Console.WriteLine("Student does not exist");
            }
        }

        private void button3_Click(object sender, EventArgs e)
        {
            if (!insertReady)
            {
                button3.Text = "Enroll";
                //ClearFields();
                textBox1.Text = getnextid().ToString();

                textBox1.Enabled = false;
                textBox2.Enabled = true;
                textBox3.Enabled = true;
                textBox4.Enabled = true;

                button1.Enabled = false;
                button2.Enabled = false;
                button4.Enabled = false;

                insertReady = true;
            }
            else
            {
                button3.Text = "Add text";
                command.Parameters.Clear();
                command.Parameters.AddWithValue("@Name", textBox2.Text);
                command.Parameters.AddWithValue("@Age", textBox3.Text);
                command.Parameters.AddWithValue("@Course", textBox4.Text);
                command.CommandText = "INSERT INTO Student_details name " + "(Name,Age,course) VALUES " +
                 "(@Name, @Age, @course)";
               
                try
                {
                    connection.Open();

                    int result = command.ExecuteNonQuery();

                    if (result > 0)
                        Console.WriteLine("student successfully enrolled");
                    else
                        Console.WriteLine("Failed to enroll the student");

                }
                catch (SqlException ex)
                {
                    MessageBox.Show(ex.Message);
                }
                finally
                {
                    connection.Close();
                }

                textBox1.Enabled = true;
                textBox2.Enabled = false;
                textBox3.Enabled = false;
                textBox4.Enabled = false;
                button1.Enabled = true;
                button2.Enabled = true;
                button4.Enabled = true;
                insertReady = false;
            }
        }

            private void ClearFields()
            {
                textBox1.Text=String.Empty;
                textBox2.Text=String.Empty;
                textBox3.Text=String.Empty;
                textBox4.Text=String.Empty;
            }

            private int getnextid()
            {
                command.CommandText="SELECT IDENT_CURRENT(''StudentID'')+IDENT_INCR(''StudentID'')";

                try
                {
                    connection.Open();
                    int nextID=Convert.ToInt32(command.ExecuteScalar());
                    return nextID;
                }
                catch(SqlException ex)
                {
                    MessageBox.Show(ex.Message);
                }
                finally
                {
                    connection.Close();
                }
                return 0;
            }

            private void button2_Click(object sender, EventArgs e)
            {
                if (!updateReady)
                {
                    button2.Text = "update";
                    textBox1.Enabled = false;
                    textBox2.Enabled = true;
                    textBox3.Enabled = true;
                    textBox4.Enabled = true;

                    button1.Enabled = false;
                    button3.Enabled = false;
                    button4.Enabled = false;

                    updateReady = true;
                }
                else
                {
                    button2.Text = "edit";
                    command.CommandText = "SELECT * FROM student name";
                    dataset.Tables.Clear();
                    adapter.Fill(dataset, "student name");

                    foreach (DataRow srow in dataset.Tables["student name"].Rows)
                    {
                        if (srow["StudentID"].ToString() == textBox1.Text)
                        {
                            srow["Name"] = textBox2.Text;
                            srow["Age"] = textBox3.Text;
                            srow["course"] = textBox4.Text;
                        }
                    }
                    try
                    {
                        int result = adapter.Update(dataset, "students");

                        if (result > 0)
                            MessageBox.Show("Update successful.");
                        else
                            MessageBox.Show("Failed to update.");
                    }
                    catch (SqlException ex)
                    {
                        MessageBox.Show(ex.Message);
                    }


                    textBox1.Enabled = true;
                    textBox2.Enabled = false;
                    textBox3.Enabled = false;
                    textBox4.Enabled = false;

                    button1.Enabled = true;
                    button3.Enabled = true;
                    button4.Enabled = true;
                    updateReady = false;

                }
            }

            private void button4_Click(object sender, EventArgs e)
            {
                command.CommandText = "SELECT * FROM Student details";
                dataset.Tables.Clear();
                adapter.Fill(dataset, "students");


                foreach (DataRow srow in dataset.Tables["students"].Rows)
                {
                    if (srow["StudentID"].ToString() == textBox1.Text)
                    {
                        srow.Delete();
                        break;
                    }
                }

                try
                {
                    int result = adapter.Update(dataset, "students");

                    if (result > 0)
                        MessageBox.Show("Student successfully deleted.");
                    else
                        MessageBox.Show("Failed to delete student.");
                }
                catch (SqlException ex)
                {
                    MessageBox.Show(ex.Message);
                }

                command.CommandText = "SELECT * FROM student details ";
                adapter.Fill(dataset, "Students");
            }

            private void textBox1_TextChanged(object sender, EventArgs e)
            {
                textBox1.Focus();
            }

            
            
        }
    }





how do i proceed?

推荐答案


选中此示例将为您提供指导
Hi ,
Check this Example will Guide you it''s easy
DataTable GetData(int id)
        {
            DataTable dt = new DataTable();
            using (SqlConnection con = new SqlConnection(Properties.Settings.Default.con))
            {
                con.Open();
                using (SqlCommand cmd = new SqlCommand("select * from test where id = @id",con))
                {
                    cmd.Parameters.AddWithValue("@id", id);
                    SqlDataAdapter adpt = new SqlDataAdapter(cmd);
                    adpt.Fill(dt);
                }            
            }
            return dt;
        }

        private void button1_Click(object sender, EventArgs e)
        {
            DataTable dt = GetData(Convert.ToInt32(txtId.Text));
            txtName.DataBindings.Add("Text", dt, "name");
        }


最好的问候
M.Mitwalli


Best Regards
M.Mitwalli


您需要编写代码.您需要编写代码以获取数据,将其放入表单元素,并在数据发生更改或要添加新值时将其写回.没有神奇的绑定"可以使您不必编写程序.可能会有一些向导在不同的框架中创建基本功能(例如带有EF的MVC3),但是您仍然需要对其进行更改以使其能够执行所需的操作.
You need to write code. You need to write code to get the data, to put it in to the form elements and to write it back if it changes, or if you want to add a new value. There is no magical ''binding'' that saves you from having to program. There might be some wizards that create basic functionality in different frameworks ( like MVC3 with EF ), but you still need to change it to make it do what you need.


这篇关于将Windows窗体绑定到sql服务器数据库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆