C# 如何将gridview中的值插入数据库
我在SQL Server数据库中有两个表。我从tableC# 如何将gridview中的值插入数据库,c#,asp.net,sql-server,C#,Asp.net,Sql Server,我在SQL Server数据库中有两个表。我从tableADMS中选择,我需要通过gridview插入主表,但我不知道如何使用gridview插入。请帮忙。我已经试了很多天了,但还没有通过 protected void Button3_Click1(object sender, EventArgs e) { if (RadioButton2.Checked) { SqlConnection con = new SqlConnection(MyConnectionS
ADMS
中选择,我需要通过gridview插入主表,但我不知道如何使用gridview插入。请帮忙。我已经试了很多天了,但还没有通过
protected void Button3_Click1(object sender, EventArgs e)
{
if (RadioButton2.Checked)
{
SqlConnection con = new SqlConnection(MyConnectionString);
// con.Open(); // don't need the Open, the Fill will open and close the connection automatically
SqlDataAdapter da = new SqlDataAdapter("SELECT * FROM ADMS_Machining where datetime='" + TextBox1.Text + "'", con);
mytable = new DataTable();
da.Fill(mytable);
GridView2.DataSource = mytable;
GridView2.DataBind();
}
else
{
SqlConnection con = new SqlConnection(MyConnectionString);
// con.Open(); // don't need the Open, the Fill will open and close the connection automatically
SqlDataAdapter da = new SqlDataAdapter("SELECT * FROM Machining_Master where datetime='" + TextBox1.Text + "'", con);
mytable = new DataTable();
da.Fill(mytable);
GridView2.DataSource = mytable;
GridView2.DataBind();
}
}
protected void Button4_Click(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection();
SqlCommand cmd = new SqlCommand();
String strConnString, strSQL;
strConnString = "Server=kane-pc;UID=sa;PASSWORD=1234;Database=Machining;Max Pool Size=400;Connect Timeout=600;";
//here
conn.ConnectionString = conn;
conn.Open();
cmd.Connection = conn;
cmd.CommandText = strSQL;
}
您必须首先从单元格中读取数据,然后使用SqlCommand将其插入数据库。 假设在加工主表中有M_ID和M_NAME列,则可以按如下方式向数据库插入值:
//Assuming that your id column is first column and name is second column
//get value of id and name
int mId = Convert.ToInt32(GridView2.SelectedRow.Cells[0].Text);
string mName = GridView2.SelectedRow.Cells[1].Text;
string connectionStrng = "your connection string";
string insertSql = "INSERT INTO Machining_Master (M_ID, M_NAME) VALUES (@mId, @mName)";
using (SqlConnection conn = new SqlConnection(connectionStrng))
{
using (SqlCommand cmd = new SqlCommand(insertSql, conn))
{
try
{
cmd.Parameters.Add(new SqlParameter("mId", mId));
cmd.Parameters.Add(new SqlParameter("mName", mName));
conn.Open();
cmd.ExecuteNonQuery();
}
finally
{
//Close connection
conn.Close();
}
}
}
您可以从栅格视图中提取值,具体取决于您在单元格中放置的内容
string value = this.GridView2.Rows[0].Cells[0].Text;
您还可以跟踪选定的行事件,并获得如下特定控件
protected void OnSelectedIndexChanged(object sender, EventArgs e)
{
string someValueTakenFromLabel = (GridView2.SelectedRow.FindControl("lblAnyLabelHere") as Label).Text;
// .... do something with value here
}
不过,我建议您通过一些教程了解如何使用GridView