gpt4 book ai didi

asp.net - 从两个列表框控件插入表格

转载 作者:行者123 更新时间:2023-11-29 07:06:27 25 4
gpt4 key购买 nike

我需要将 user_id 和 quiz_iz 插入到表列中,我有以下代码可用于将一个控件中的多个选定值插入到表列中,但我不知道如何从值中插入 2 个字段点击提交时会在两个控件上列出。

我正在使用 odbc 连接到 mysql,那是我需要插入的表位于....

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Collections.Specialized;
using System.Text;
using System.Data;
using System.Data.Odbc;

public partial class _Default : System.Web.UI.Page
{

protected void Page_Load(object sender, EventArgs e)
{

}

private void InsertRecords(StringCollection sc, StringCollection sc2)
{
string ConnectionString = @"driver={MySQL ODBC 5.1 Driver};server=localhost;database=db_mydb;uid=;pwd=;";
OdbcConnection conn = new OdbcConnection(ConnectionString);
StringBuilder sb = new StringBuilder(string.Empty);
StringBuilder sb2 = new StringBuilder(string.Empty);

foreach (string item in sc)
{

const string sqlStatement = "INSERT INTO jos_jquarks_users_quizzes (quiz_id,user_id) VALUES";

sb.AppendFormat("{0}('{1}'); ", sqlStatement, item);
sb2.AppendFormat("{0}('{1}'); ", sqlStatement, item);

}

try
{

conn.Open();

OdbcCommand cmd = new OdbcCommand(sb.ToString(), conn);
cmd.CommandType = CommandType.Text;
cmd.ExecuteNonQuery();
Page.ClientScript.RegisterClientScriptBlock(typeof(Page), "Script", "alert('Records Successfuly Saved!');", true);

}

catch (System.Data.SqlClient.SqlException ex)
{

string msg = "Insert Error:";
msg += ex.Message;
throw new Exception(msg);

}

finally
{

conn.Close();

}

}


protected void Button1_Click(object sender, EventArgs e)
{

StringCollection sc = new StringCollection();
StringCollection sc2 = new StringCollection();


foreach (ListItem item in ListBox1.Items)
{

if (item.Selected)
{

sc.Add(item.Text);

}

}

foreach (ListItem item in ListBox2.Items)
{

if (item.Selected)
{

sc2.Add(item.Text);

}

}
InsertRecords(sc , sc2);


}
}

最佳答案

也许你应该使用嵌套的 foreach。

foreach (string item in sc)
{
foreach (string item in sc2)
{
insert sc and sc2
}
}

关于asp.net - 从两个列表框控件插入表格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7019563/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com