简体   繁体   English

如何将数据库中的 Integer 转换为文本框中的字符串?

[英]How to convert Integer from database into string in textbox?

This is a little piece of code I wrote to autocomplete my textbox from the database as I type:这是我编写的一小段代码,用于在我键入时从数据库中自动完成我的文本框:

        {
            SqlConnection connString = new SqlConnection();
            connString.ConnectionString = "Data Source=************************;Initial Catalog=STUPELG;Persist Security Info=True;User ID=****************;Password=**********";
            SqlDataAdapter adapter = new SqlDataAdapter();
            connString.Open();
            SqlDataReader dataReader;
            SqlCommand command = new SqlCommand("SELECT Name FROM dbo.Entity WHERE Name LIKE @name", connString);
            command.Parameters.Add(new SqlParameter("@name", "%" + tbEntity.Text + "%"));
            command.ExecuteNonQuery();
            dataReader = command.ExecuteReader();
            AutoCompleteStringCollection col = new AutoCompleteStringCollection();
            while (dataReader.Read())
            {
                col.Add(dataReader.GetString(0));
            }

            tbEntity.AutoCompleteCustomSource = col;
            connString.Close();
        }

However, I want to display two fields (EntityID, Name) out of the database into the textbox, but但是,我想将数据库中的两个字段(EntityID,Name)显示到文本框中,但是

  1. I do not know how to display more than one field.我不知道如何显示多个字段。
  2. EntityID is an integer and I am not sure how to convert it to string in my code. EntityID 是 integer,我不确定如何在我的代码中将其转换为字符串。

Any suggestions?有什么建议么?

Usually a textbox is not used to display more than one data coming from the database.通常文本框不用于显示来自数据库的多个数据。 But also notice that autocomplete is a tool to help your end users to choose while typing.但也请注意,自动完成是一种帮助最终用户在输入时进行选择的工具。
If you want to add also the EntityID you need to add it after the name in the autocomplete source.如果您还想添加 EntityID,则需要在自动完成源中的名称之后添加它。

First you need to change the sql command to retrieve also the EntityID field and not just the Name field首先,您需要更改 sql 命令以检索 EntityID 字段而不仅仅是 Name 字段

string cmdText = "SELECT Name, EntityID FROM dbo.Entity WHERE Name LIKE @name";
SqlCommand command = new SqlCommand(cmdText, connString);

Then inside the loop that read the values you add both the Name and the EntityID as part of the string added to the autocomplete collection然后在读取值的循环中,您将 Name 和 EntityID 作为添加到自动完成集合的字符串的一部分添加

while (dataReader.Read())
{
    string data = $"{dataReader.GetString(0)} {dataReader.GetInt32(1)}"
    col.Add(data);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM