将列表框中的数据添加到SQL Server 2000 DB中 [英] Add data from a list box into SQL Server 2000 DB
问题描述
请任何人都可以帮助我,将列表框项添加到数据库表中,我这样做是使用以下代码,但它不能正常工作..(它是C#Windows应用程序)
Please anyone can help me out in adding the listbox items into a database table, i used the following code for doing so but it dosent work properly.. (it''s a C# windows application)
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Windows.Forms;
using System.Data;
using System.Data.SqlClient;
namespace test
{
public partial class MainForm : Form
{
public MainForm()
{
InitializeComponent();
}
void Button1Click(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection(@"User ID=username; Password=pass;
Initial Catalog=databasename; data source=localhost");
SqlCommand cmd = conn.CreateCommand();
foreach(object i in listBox1.SelectedItems)
{
cmd.CommandText = "INSERT INTO TableName (columnName) VALUES(''"+i.ToString()+"'')";
cmd.ExecuteNonQuery();
}
conn.Close();
}
}
请任何人尽快帮助我...
Pls can any one help me out as soon as possible......
推荐答案
好吧,您尝试了什么?您阅读了数千篇在线文章中的哪一篇?您读过几百本书中的哪几本书?在要求我们为您执行此操作之前,您如何尝试自己完成此操作?
Well, what have you tried ? Which of the thousands of online articles on this have you read ? Which of the hundreds of books printed have you read ? How have you tried to do this for yourself before asking us to do it for you ?
您遵循的方法不好,但仍然可以这样做,因为遵循您的代码将可以正常工作.
Approach you are following is not good, but still by doing as following your code will work.
foreach(ListItem i in listBox1.SelectedItem)
{
cmd.CommandText = "INSERT INTO TableName (columnName) VALUES(''"+i.Text)+"'')";
cmd.ExecuteNonQuery();
}
您可以根据需要使用i.Text
或i.Value
.
您应该按照以下步骤进行操作.
为所有项目创建一个XML文档,并将xml传递给数据库,以便您可以在单个datbase行程中插入所有项目.
You can use either i.Text
or i.Value
as per your requirement.
You should have been done this as following.
Create a XML document for all the items and pass the xml to the DB, so that you can insert all the items in a single datbase trip.
SqlConnection mycn;
SqlDataAdapter myda;
DataSet ds;
String strConn;
private void Page_Load(object sender, System.EventArgs e)
{
if (!IsPostBack)
{
strConn="Data Source=localhost;uid=sa;pwd=;Initial Catalog=database";
mycn = new SqlConnection(strConn);
myda = new SqlDataAdapter ("Select * FROM Table ", mycn);
ds = new DataSet();
myda.Fill (ds,"Table");
DropDownList1.DataSource =ds.Tables [0] ;
DropDownList1.DataTextField =ds.Tables[0].Columns["Name"].ColumnName.ToString();
DropDownList1.DataValueField =ds.Tables[0].Columns["Id"].ColumnName.ToString();
DropDownList1.DataBind () ;
}
}
选择选中此选项,然后尝试插入记录..希望这会对您有所帮助.
祝你好运
I m giving the code for select check this and try to insert the record .. Hope this will help you.
Good Luck
这篇关于将列表框中的数据添加到SQL Server 2000 DB中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!