我需要一些帮助才能完成此操作。我已经搜索并尝试了几种方法,但在我的头脑中却没有。这不是功课!我是一名自学者。
我设法填充了一个从下拉列表中选择表格的网格:
private void radDropDownList1_SelectedIndexChanged(object sender, Telerik.WinControls.UI.Data.PositionChangedEventArgs e)
{
if (radDropDownList1.SelectedIndex > 0)
{
radGridView1.Visible = true;
label8.Text = radDropDownList1.SelectedValue.ToString();
DataTable dt = new DataTable();
var selectedTable = radDropDownList1.SelectedValue; //Pass in the table name
string query = @"SELECT * FROM " + selectedTable;
using (var cn = new SqlConnection(connString))
{
cn.Open();
try
{
SqlCommand cmd = new SqlCommand(query, cn);
using (var da = new SqlDataAdapter(cmd))
{
da.Fill(dt);
}
}
catch (SqlException ex)
{
//MessageBox.Show(ex.StackTrace);
}
}
radGridView1.DataSource = dt;
}
现在我正在尝试编写事件以使用网格作为数据源来更新sql表:
private void radGridView1_CellEndEdit(object sender, Telerik.WinControls.UI.GridViewCellEventArgs e)
{
DataTable dt = (DataTable)radGridView1.DataSource;
DataSet ds = new DataSet();
ds.Tables[0] = dt;
try
{
//**I am lost here!**
}
catch
{
}
}
你可以帮忙吗?我现在如何更新sql表?
答案 0 :(得分:1)
我不太喜欢你管理更新的方式,但......这段代码会发送更新声明:
using (var cn = new SqlConnection(connString))
{
cn.Open();
try
{
SqlCommand cmd = new SqlCommand("UPDATE YourTable SET Column = @Parm1 WHERE Col = @Parm2", cn);
var parm1 = cmd.CreateParameter("Parm1");
parm1.Value = "SomeValue";
var parm2 = cmd.CreateParameter("Parm2");
parm2.Value = "SomeOtherValue";
cmd.Parameters.Add(parm1);
cmd.Parameters.Add(parm2);
int rowsAffected = cmd.ExecuteNonQuery();
}
catch (SqlException ex)
{
//MessageBox.Show(ex.StackTrace);
}
}