C#原代码(使用sql数据库)
最佳答案
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
namespace LoginApp
{
public partial class RegForm : Form
{
public RegForm()
{
InitializeComponent();
}
//窗体加载的时候执行的代码
private void RegForm_Load(object sender, EventArgs e)
{
//for (int i = 15; i < 25; i++)
//{
// this.comboBox1.Items.Add(i);
//}
string strcon = "server=localhost;database=studb;uid=sa;pwd=";
SqlConnection con = new SqlConnection(strcon);
SqlCommand cmd = new SqlCommand("select age from test",con);
con.Open();
SqlDataReader datareader = cmd.ExecuteReader();
while (datareader.Read())
{
this.comboBox1.Items.Add(datareader.GetInt32(0));
}
con.Close();
}
//增加按钮
private void button1_Click(object sender, EventArgs e)
{
//注意未填写数据的处理,本代码中未设置
string strcon = "server=localhost;database=studb;uid=sa;pwd=";
DataSet ds = new DataSet();//内存中的空间
SqlDataAdapter adapter = new SqlDataAdapter("select * from customer",strcon);//适配器
adapter.Fill(ds,"customer");//填充空间
string sex = "";
if (this.radioButton1.Checked)
{
sex = "male";
}
else
{
sex = "female";
}
string age=Convert.ToString(this.comboBox1.SelectedItem);
SqlConnection con=new SqlConnection(strcon);//数据库连接
con.Open();
string stradd = "insert into customer(cid,cname,pwd,sex,age,address)"+
"values('"+this.textBox4.Text.Trim()+"','"+this.textBox1.Text.Trim()+
"','"+this.textBox2.Text.Trim()+"','"+sex+"',"+age+",'"+
this.textBox5.Text.Trim()+"')";//加入数据库
SqlCommand cmd = new SqlCommand(stradd,con);
adapter.InsertCommand = cmd;
adapter.InsertCommand.ExecuteNonQuery();
con.Close();
}
//查看表中信息
int count = -1;
int r = -1;
private void button2_Click(object sender, EventArgs e)
{
string strcon = "server=localhost;database=studb;uid=sa;pwd=";
DataSet ds = new DataSet();
SqlDataAdapter adapter = new SqlDataAdapter("select * from customer", strcon);//适配器
adapter.Fill(ds, "customer");
DataTable dt = ds.Tables[0];
if (count == -1)
{
count = dt.Rows.Count;//多少行
count = dt.Columns.Count; //多少列
}
if (r == -1||r==count)
{
r = 0;
}
DataRow dr = dt.Rows[r];
this.textBox4.Text = Convert.ToString(dr["cid"]);
this.textBox1.Text = Convert.ToString(dr["cname"]);
this.textBox2.Text = Convert.ToString(dr["pwd"]);
if(Convert.ToString(dr["sex"]).Equals("male")){
this.radioButton1.Checked=true;
}else{
this.radioButton2.Checked=true;
}
this.comboBox1.SelectedItem=dr["age"];
this.textBox5.Text=Convert.ToString(dr["address"]);
r++;
}
private void button3_Click(object sender, EventArgs e)
{
new Form1().Show();
}
}
}