我对c#语言更新。现在我的项目是将数据从数据库提取到datagridview并添加编辑和删除列。
我在表学生中有5个字段(id,姓名,学位,大学,城市)
这里是我的代码:
MySqlConnection connection = new MySqlConnection("SERVER=hostaddress","DATABASE=DTBS","UID=UID","PASSWORD=PWDS");
MySqlCommand command = new MySqlCommand("SELECT * from student;", connection);
connection.Open();
DataTable dataTable = new DataTable();
MySqlDataAdapter da = new MySqlDataAdapter(command);
da.Fill(dataTable);
dataGridView1.DataSource = dataTable;
现在我需要在datagridview上添加编辑和删除列的帮助。 当我点击datagridview上的编辑时,我需要在表单2上获取行数据,我不明白它是什么,我该怎么做。我在谷歌搜索更多。但我没有得到一个明确的解释,它有助于我进行一些编码。
答案 0 :(得分:4)
试试这个编码:
public partial class Form2 : Form
{
// for this we can reload after closing the form 2 the datagridview get refresh
Form1 _owner;
public Form2()
{
InitializeComponent();
}
public Form2(Form1 owner)
{
InitializeComponent();
_owner = owner;
this.FormClosing += new System.Windows.Forms.FormClosingEventHandler(this.Form2_FormClosing);
}
String MyCon = "SERVER=*******;" +
"DATABASE=dtbas;" +
"UID=userid;" +
"PASSWORD=paswrd;" + "Convert Zero Datetime = True";
public string a
{
get { return txtid.Text; }
set { txtid.Text = value; }
}
private void Form2_FormClosing(object sender, FormClosingEventArgs e)
{
_owner.data();
}
private void Form2_Load(object sender, EventArgs e)
{
MySqlConnection con = new MySqlConnection(MyCon);
con.Open();
MySqlCommand Com = new MySqlCommand("Select * from student where id ='" + txtid.Text + "'", con);
MySqlDataReader dt = Com.ExecuteReader();
if (dt.Read())
{
// i assume (id textBox as txtid),(name textbox as txtname),(degree textbox as txtdegree),(college textbox as txtcollege),(city textbox as txtcity)
txtid.Text = dt.GetValue(0).ToString();
txtname.Text = dt.GetValue(1).ToString();
txtdegree.Text = dt.GetValue(2).ToString();
txtcollege.Text = dt.GetValue(3).ToString();
txtcity.Text = dt.GetValue(4).ToString();
con.Close();
}
//button in form2 to save it in the database. (button as btnsave)
private void btnsave_Click(object sender, EventArgs e)
{
MySqlConnection con = new MySqlConnection(MyCon);
con.Open();
string query = string.Format("Update student set id='" + txtid.Text + "' , name='" + txtname.Text + "' , degree='" + txtdegree.Text + "' , college='" + txtcollege.Text + "' , city='" + txtcity.Text + "'where id='" + txtid.Text + "'");
MySqlCommand cmd = new MySqlCommand(query, con);
cmd.ExecuteNonQuery();
}
}
}
表格2:
import csv
lines = ['"hello world." here are some words. "and more"']
list(csv.reader(lines, delimiter=' ', quotechar='"'))
Refrence:http://www.dotnetsharepoint.com/2013/07/how-to-add-edit-and-delete-buttons-in.html
它会帮助你。