C# 更新表,其中动态选择列名-DropDown.SelectedValue
我想更新将下拉ColumnName的表的列。SelectedValue 示例:将从Customer表中显示一组记录,其中CUstNo='1234'和City='Chicago'和Grade='B' 一旦显示,我想根据上述标准将所有客户的等级更新为“A” 在我的例子中,我有大约100列,因此在where子句中,将从DaropDown中选择列名 在我的查询中,更新客户集ColumnName='some value',其中ColumnName='ActualValue' 那么我如何传递ColumnName,它是下拉选择的值 我相信我不能像你一样付出 更新客户集下拉列表。SelectedValue='some value',其中DropDown.SelectedValue='ActualValue'C# 更新表,其中动态选择列名-DropDown.SelectedValue,c#,vb.net,C#,Vb.net,我想更新将下拉ColumnName的表的列。SelectedValue 示例:将从Customer表中显示一组记录,其中CUstNo='1234'和City='Chicago'和Grade='B' 一旦显示,我想根据上述标准将所有客户的等级更新为“A” 在我的例子中,我有大约100列,因此在where子句中,将从DaropDown中选择列名 在我的查询中,更新客户集ColumnName='some value',其中ColumnName='ActualValue' 那么我如何传递ColumnNa
我如何解决这个问题?..听起来您想基于网格构建动态sql?如果是这样的话,你可以随时做类似的事情
string updateStmt = String.Format("UPDATE Customer SET {0} = 'some value' WHERE...", dropDown.SelectedValue);
然后你可以执行这个语句。我真的不知道你在用什么,但是有更好的方法来更新数据库。你可以使用ORM或者甚至可以使用
编辑:下面是ASP.NET中的一个示例,尽管winform应用程序非常类似
假设此dropdownlist是从某个数据源填充的
<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>
如果选择了Col1,则初始化字符串后update语句字符串将如下所示:
"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;
}
谢谢你的答复。。我的客户机正在使用.NET2.0,因此无法获取ORM。在上面代码集{0}的片段中,它如何知道columnName,因为columnName将从DropDownList中选择,甚至在where子句中,我如何给出columnName。列名将由用户从DropdownList中动态选择。在没有看到代码的情况下很难判断程序的外观,但我假设DropdownList中的值是列名,因此,当用户从dll中选择一个值时,会触发一些事件,在您的事件处理程序中,您可以根据他们在下拉列表中选择的值构建动态sql。您好,再次感谢您的回复。是的,当我从ddl中选择值时,这是正确的。。。。如何构建动态sql?因为在动态sql中,我应该如何以编程方式给出列名?我用ASP.NET中的一个示例更新了我的答案。我想在UpdateButton\u Click事件处理程序中更新。。。所以我可以用那个片段。。。。我正在使用ComboBox{Winforms},所以它没有ListItem,我尝试使用它的ITEM属性,但它对我不起作用。我想让它更简单,而不是从ComboBox中获取ColumnAM让我获取一些Label.Text值。。。。当我将Label1.Text作为ColumnName时,SQL Excelion被抛出,因为它没有被识别。。。。。任何选择。。。。。若我至少可以传递Label1.Text值作为ColumnName,那个就足够了
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;
}