代码之家  ›  专栏  ›  技术社区  ›  msbyuva

更新表,其中动态选择列名称-下拉列表。SelectedValue

  •  0
  • msbyuva  · 技术社区  · 15 年前

    我想更新一个表的列,其中columnname将下拉。selectedValue。

    示例:将从客户表中显示一组记录,其中custno='1234'和city='chicago'和grade='b'

    一旦显示,我想根据上述标准将所有客户的等级更新为“A”。

    在我的例子中,我有100个列,所以在WHERE子句中,列名称将从daropdown中选择。

    在我的查询中,更新customer set columnname='some value'其中columnname='actualvalue'

    那么,如何传递下拉选择值的columnname呢?

    我相信我不能像 更新customer set dropdown.selectedvalue='some value'其中dropdown.selectedvalue='actualvalue'

    我如何解决这个问题?…

    1 回复  |  直到 9 年前
        1
  •  2
  •   Matt Dearing    15 年前

    所以听起来您想基于网格构建动态SQL?如果是这样的话,你可以做一些像

    string updateStmt = String.Format("UPDATE Customer SET {0} = 'some value' WHERE...", dropDown.SelectedValue);
    

    然后您可以执行这个语句。我真的不知道你在使用什么,但是有更好的方法来更新数据库。你可以用像ORM这样的 Linq to Sql Entity Framework 或者你甚至可以用 SqlCommandBuilder

    编辑: 下面是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>
    

    在事件处理程序中,基于所选列生成updateStation

    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语句字符串将如下所示:

    "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;
        }