所以听起来您想基于您的网格构建动态 sql?如果是这样的话,你总是可以做类似的事情
string updateStmt = String.Format("UPDATE Customer SET {0} = 'some value' WHERE...", dropDown.SelectedValue);
然后你就可以执行这个语句了。我真的不知道你在使用什么,但有更好的方法来进行数据库更新。你可以使用像 Linq to Sql 或 Entity Framework 这样的 ORM,或者你甚至可以使用像 SqlCommandBuilder 这样的东西
编辑:这是 ASP.NET 中的一个示例(尽管 winform 应用程序非常相似)
假设这个下拉列表是从某个数据源填充的
<form id="form1" runat="server" method="post" target="Default2.aspx">
<asp:DropDownList ID="test" runat="server" AutoPostBack="true" OnSelectedIndexChanged="test_SelectedIndexChanged">
<asp:ListItem Value="" Selected="True"/>
<asp:ListItem Value="Col1"/>
<asp:ListItem Value="Col2"/>
<asp:ListItem Value="Col3"/>
</asp:DropDownList>
</form>
在事件处理程序中根据所选列构建 updateStatement
protected void test_SelectedIndexChanged(object sender, EventArgs e)
{
string updateStatement = String.Format("UPDATE Customer SET {0} = 'some value' WHERE {0} = 'some other value'", test.SelectedValue);
//execute the updatestatement;
}
字符串初始化后更新语句字符串如下所示(如果选择了Col1):
"UPDATE Customer SET Col1 = 'some value' WHERE Col1 = 'some other value'"
编辑 2:好的,这是一个 winforms 应用程序中的示例
首先,我在组合框中添加了一些值。接下来,当单击表单上的按钮时,我从组合框中获取所选值并将其用于动态 sql 字符串。它将为您提供与上述 asp.net 解决方案相同的结果。
public Form1()
{
InitializeComponent();
//add values to combobox from some datasource
comboBox1.Items.Add("Col1");
comboBox1.Items.Add("Col2");
comboBox1.Items.Add("Col3");
}
private void button1_Click(object sender, EventArgs e)
{
string updateStatement = String.Format("UPDATE Customer SET {0} = 'some value' WHERE {0} = 'some other value'", comboBox1.SelectedItem);
//execute the updatestatement;
}