数据库(sql2008 express)(ASP inC#) [英] Database(sql2008 express)(ASP inC#)

查看:109
本文介绍了数据库(sql2008 express)(ASP inC#)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我写了这段代码片段,但我没有任何结果。

编译后,我在ListBox中没有任何数据。

数据库中的表还有数据。

请帮帮我谢谢。

hi , i wrote this code snippet, but i have not any result.
after compile, i have not any data in the ListBox.
Table in the database also have data.
please help me thank you.

public partial class _Default : System.Web.UI.Page 
{
    private string connectinString=
        WebConfigurationManager.ConnectionStrings["Pubs"].ToString();
    protected void Page_Load(object sender, EventArgs e)
    {
       if(!IsPostBack)
       {
           FillAuthorList();
       }
    }  
      private void FillAuthorList()
      {
         lstItems.Items.Clear();
         string SelectSQL="SELECT id, au_lname, au_fname FROM Authors";
          SqlConnection con = new SqlConnection(connectinString);
          SqlCommand command = new SqlCommand(SelectSQL, con);
          SqlDataReader reader;
          
          try
          {
              con.Open();
              reader = command.ExecuteReader();
              reader.Read();
              while (reader.Read())
              {
                  ListItem newItem=new ListItem();
                  newItem.Text=reader["au_lname"]+","+reader["au_fname"];
                  newItem.Value=reader["id"].ToString();
                  lstItems.Items.Add(newItem);
              }
            reader.Close();
          }
          catch(Exception Err)
          {
              lblResult.Text="Error reading list";
              lblResult.Text+=Err.Message;
          }

          con.Close();  
            }
}





已添加代码块[/编辑]



Code block added[/Edit]

推荐答案

首先,如果你的数据库表中只有一条记录,那么你什么也得不到 - 因为你放弃了你读过的第一条记录:

First off, if you only have one record in your DB table, then you will get nothing - because you discard the first record you read:
reader.Read();
while (reader.Read())

每次调用Read方法时,都会替换当前记录与下一个。摆脱这两个的第一行只留下循环。



其次,我也会建议显式转换:

Every time you call the Read method, the current record is replaced with the next. Get rid of the first line of these two to leave just the while loop.

Secondly, I would also recommend explicit casting:

newItem.Text=(string) reader["au_lname"] + "," + (string) reader["au_fname"];



你不需要它(因为可能会进行隐式的ToString调用),但值得做的是从可读性和类型安全点到查看。



如果您有多行数据,那么您需要查看您的lblResult标签 - 您收到任何消息吗?这应该会有所帮助。


You don''t need it (as implicit ToString calls will probably be made), but it is worth doing from a readability and type safety point of view.

If you have more than one row of data, then you need to look at your lblResult label - do you get any message? That should help.


这篇关于数据库(sql2008 express)(ASP inC#)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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