我如何用数据库结果填充列表框. [英] how do i populate a listbox with results from a database.

查看:45
本文介绍了我如何用数据库结果填充列表框.的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何用数据库结果填充listobx.我想从数据库中选择一个ID和一个名称,并使用能够从显示数据库搜索结果的列表框中访问ID.在下面的代码中,我尝试将结果放入数据库中,并从数据表内容填充列表框.但它似乎不起作用.有帮助吗?

how do i populate a listobx with results from a database. I want to select an id and a name from the database and use the be able to access the id from the listbox in which the results of the db search are displayed. in the code below i try to put the results in a database and the populate the listbox from the data table contents. but it doesnt seem to work. any help?

String connection, sql;
connection = Properties.Settings.Default.cvmanagerConnectionString;


sqlA = "select FileLoc, Lname from apps where dept = '" + intdept.Text + "' and role = '" + introle.Text + "' and rating = '" + intratinglevel.Text + "' and yearsofexp = '" + intexp.Text + "' and hnd = '" + edulev.Text + "' ";
           
            //datatable creation for storing search results
            DataTable results = new DataTable("searchResults");
            DataColumn column;
            DataRow row;

            column = new DataColumn();
            column.DataType = System.Type.GetType("System.Int32");
            column.ColumnName = "apps";
            column.ReadOnly = true;
            column.Unique = true;
            results.Columns.Add(column);


            column = new DataColumn();
            column.DataType = System.Type.GetType("System.String");
            column.ColumnName = "LastName";
            column.ReadOnly = true;
            column.Unique = true;
            results.Columns.Add(column);

            DataColumn[] PrimaryKeyColumns = new DataColumn[1];
            PrimaryKeyColumns[0] = results.Columns["apps"];
            results.PrimaryKey = PrimaryKeyColumns;

            cvmanagerDataSet1.Tables.Add(results);



            SqlDataReader reader = null;
            SqlConnection conn = new SqlConnection(connection);
            SqlCommand cmd = new SqlCommand(sql, conn);

            try
            {
                conn.Open();
                reader = cmd.ExecuteReader();
                intsearchresults.Enabled = true;

                while (reader.Read())
                {                                                           
                    row = results.NewRow();
                    row["apps"] = reader["apps_id"].ToString();
                    row["LastName"] = reader["Lname"].ToString();
                    results.Rows.Add(row);

                intsearchresults.Items.Add(reader["Lname"].ToString());
                    
                }

            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
            finally
            {
                reader.Close();
                conn.Close();

            }

        }



[edit]整理一下代码块-OriginalGriff [/edit]



[edit]Just a tidy on the code block - OriginalGriff[/edit]

推荐答案

似乎有些地方可以引起注意:
1.您将 sql 声明为字符串,但是将所构建的选择查询分配给名为 sqlA 的变量,该变量从未使用过.
2.创建新行并在此处为其分配值时:
There seem to be few spots that could use some attention:
1. You declared sql as a string but you assign the select query that you built to a variable called sqlA, which never gets used.
2. When you create the new row and assign values to it here:
while (reader.Read())
                {
                    row = results.NewRow();
                    row["apps"] = reader["apps_id"].ToString();
                    row["LastName"] = reader["Lname"].ToString();
                    results.Rows.Add(row);
                intsearchresults.Items.Add(reader["Lname"].ToString());
                }


读者从未输入名为"apps_id"的列,但您的select语句确实选择了名为"FileLoc"的列.
3.在您的where子句中:


the reader never took in a colomn named ''apps_id'', but your select statement does select a column named ''FileLoc''.
3. In your where clause:

" where dept = ''" + intdept.Text + "'' and role = ''" + introle.Text + "'' and rating = ''" + intratinglevel.Text + "'' and yearsofexp = ''" + intexp.Text + "'' and hnd = ''" + edulev.Text + "'' "


controls(TextBox?)名称似乎表明它们是整数.如果是这种情况,则意味着值以整数形式存储在数据库中,那么您就不想将它们用单引号引起来.

希望对您有所帮助.


the controls(TextBox?) names seem to indicate that they are integers. If this is the case, meaning the values are stored in the database as integers, then you do not want to wrap them in single quote marks.

Hope this helps.


我给您的最好的样品之一.根据您的需要进行较小的更改.
Default2.aspx

< body>
< form id ="form1" runat ="server">
< div>
< asp:ListBox ID ="ListBox1" runat ="server"></asp:ListBox>
</div>
</form>
</body>
</html>

================================================== ==============

Default2.aspx.cs

使用System.Data.SqlClient;
使用System.Data;

公共局部类Default2:System.Web.UI.Page
{
受保护的void Page_Load(对象发送者,EventArgs e)
{

如果(!this.IsPostBack)
{
字符串strConnectionString =
数据源=.\\ sqlexpress;初始目录= CPTempDB;集成安全性= True;池= False";
SqlConnection con =新的SqlConnection(strConnectionString);
字符串strQuery ="SELECT * FROM Student";
SqlCommand cmd =新的SqlCommand(strQuery,con);

//SqlDataAdapter da =新的SqlDataAdapter(cmd); OOORRR
SqlDataAdapter da =新的SqlDataAdapter();
da.SelectCommand = cmd;

DataSet ds = new DataSet();

试试
{
con.Open();
da.Fill(ds);
}
catch(异常err)
{
//处理抛出的异常
}
终于
{
con.Close();
}

ListBox1.DataSource = ds.Tables [0];
ListBox1.DataValueField ="ID";
ListBox1.DataTextField =名称";
ListBox1.DataBind();
}

}
}
One of the best sample I am giving you. Make minor changes according to u r needs.
Default2.aspx

<body>
<form id="form1" runat="server">
<div>
<asp:ListBox ID="ListBox1" runat="server"></asp:ListBox>
</div>
</form>
</body>
</html>

=================================================================

Default2.aspx.cs

using System.Data.SqlClient;
using System.Data;

public partial class Default2 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{

if (!this.IsPostBack)
{
String strConnectionString =
"Data Source=.\\sqlexpress;Initial Catalog=CPTempDB;Integrated Security=True;Pooling=False";
SqlConnection con = new SqlConnection(strConnectionString);
String strQuery = "SELECT * FROM Student";
SqlCommand cmd = new SqlCommand(strQuery, con);

//SqlDataAdapter da = new SqlDataAdapter(cmd); OOORRR
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = cmd;

DataSet ds = new DataSet();

try
{
con.Open();
da.Fill(ds);
}
catch (Exception err)
{
// Handle the exception thrown
}
finally
{
con.Close();
}

ListBox1.DataSource = ds.Tables[0];
ListBox1.DataValueField = "ID";
ListBox1.DataTextField = "Name";
ListBox1.DataBind();
}

}
}


这篇关于我如何用数据库结果填充列表框.的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆