【发布时间】:2016-01-22 23:56:26
【问题描述】:
我刚开始使用 Visual Studio 2015 学习 C#,我的任务是创建一个彩票程序,将生成的数字保存到数据库中。我尝试了各种方法,但它们似乎都没有为我的桌子添加任何东西。任何人都可以帮助我了解我需要做什么,取一个已生成并转换为字符串/文本框的整数,然后将该值插入我的表中。
下面是我当前的代码,按钮 2 是我试图用来保存文本框中数据的按钮。
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.Windows.Forms;
using System.Configuration;
using System.Data.SqlClient;
namespace WindowsFormsApplication2
{
public partial class Form1 : Form
{
//Database details
string connectionString;
SqlConnection connection;
public Form1()
{
InitializeComponent();
connectionString = ConfigurationManager.ConnectionStrings["WindowsFormsApplication2.Properties.Settings.LottoConnectionString"].ConnectionString;
}
private void button1_Click(object sender, EventArgs e)
{
Random rnd = new Random();
int[] slot = new int[6];
int counter = 0;
for (int i = 0; i < slot.Length; i++)
{
slot[i] = rnd.Next(0, 100);
}
//Converting generated ints to Strings for display
textBox1.Text = (slot[0].ToString());
textBox2.Text = (slot[1].ToString());
textBox3.Text = (slot[2].ToString());
textBox4.Text = (slot[3].ToString());
textBox5.Text = (slot[4].ToString());
textBox6.Text = (slot[5].ToString());
//Incrementing Counter checks matches
if (numericUpDown1.Value == slot[0])
{
counter += 1;
}
if (numericUpDown2.Value == slot[1])
{
counter += 1;
}
if (numericUpDown3.Value == slot[2])
{
counter += 1;
}
if (numericUpDown4.Value == slot[3])
{
counter += 1;
}
if (numericUpDown5.Value == slot[4])
{
counter += 1;
}
if (numericUpDown6.Value == slot[5])
{
counter += 1;
}
//display total matches
textBox7.Text = ("You got" + counter + "/6 matches!");
LottoDataSetTableAdapters.ResultsTableAdapter resultsTableAdapter =
new LottoDataSetTableAdapters.ResultsTableAdapter();
resultsTableAdapter.Insert((slot[0].ToString()), (slot[1].ToString()), (slot[2].ToString()), (slot[3].ToString()), (slot[4].ToString()), (slot[5].ToString()));
}
private void button2_Click(object sender, EventArgs e)
{
// Adding Data to Database
string query = "INSERT INTO Results VALUES (@First)";
using (connection = new SqlConnection(connectionString))
using (SqlCommand command = new SqlCommand(query, connection))
{
connection.Open();
command.Parameters.AddWithValue("@First", textBox1.Text);
command.Parameters.AddWithValue("@Second", textBox2.Text);
command.Parameters.AddWithValue("@Third", textBox3.Text);
command.Parameters.AddWithValue("@Fourth", textBox4.Text);
command.Parameters.AddWithValue("@Fifth", textBox5.Text);
command.Parameters.AddWithValue("@Sixth", textBox6.Text);
}
}
}
}
我们将不胜感激所有帮助。
【问题讨论】:
-
请包括结果表的定义。结果表是单列吗?