如何从数据库读取数据并存储到数组C# [英] How to read data from database and store to an array C#

查看:1341
本文介绍了如何从数据库读取数据并存储到数组C#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用数据库值制作动态标签。

我已经制作了这些标签。但我希望这些标签用tbl_categories填充为子标题而不是label1,2,3。< br $> b $ b

我的尝试:



I want to make dynamic labels using database values.
I already made those labels.But I want that labels to be filled with tbl_categories as a sub titles instead of label1,2,3.

What I have tried:

public partial class Form1 : Form
	{

		static string mycon = ConfigurationManager.ConnectionStrings["connstrng"].ConnectionString;

		public Form1()
		{
			InitializeComponent();
		}
		
		private void Form1_Load(object sender, EventArgs e)
		{
			SqlConnection conn = new SqlConnection(mycon);
			
			
			string sql = " SELECT COUNT(*) FROM tbl_categories";
			SqlCommand cmd = new SqlCommand(sql, conn);
			

			conn.Open();
			int count = (int) cmd.ExecuteScalar();
			
		

			for (int i = 0; i < count; i++)
			{
				
				Label l = addLabel(i);
				flowLayoutPanel1.Controls.Add(l);
			}
		
		

		}
		
		Label addLabel(int i)
		{
			Label l = new Label();
			l.Name = "label" + i.ToString();
			l.Text = "label" + i.ToString();
			l.ForeColor = Color.White;
			l.BackColor = Color.Blue;
			l.Font = new Font("Serif", 24, FontStyle.Bold);
			l.Width = 170;
			l.Height = 80;
			
			l.TextAlign = ContentAlignment.MiddleCenter;
			l.Margin = new Padding(5);

			return l;
		}
	}

推荐答案

任务不是太难;您将需要调整 addlabel 方法以接受字符串输入;以及确定要在其中填充SQL的文本
Not too hard of a task; you are going to need to adjust your addlabel method to accept a string input; as well as determine what text from SQL you want to populate it
private void Form1_Load(object sender, EventArgs e) {

   using (SqlConnection conn = new SqlConnection(mycon)) {
      
      // change to whichever column contains label name
      string sql = "SELECT [LabelName] FROM tbl_categories"; 

      SqlComand cmd = new SqlComand(sql, conn);

      conn.Open();
      
//      int count = (int) cmd.ExecuteScalar();
//      for (int i = 0; i < count; i++) {
//         Label l = addLabel(i);
//         flowLayoutPanel1.Controls.Add(l);
//      }

           SqlDataReader reader = comand.ExecuteReader();
           if (reader.HasRows) {
             while (reader.Read()) {

               // TODO: Change label to accept string input
               Label l = addLabel(reader.GetString(0));

               flowLayoutPanel1.Controls.Add(l);
         }
      }
      conn.Close();
   }
}





MS文档:使用DataReader检索数据Microsoft Docs [ ^ ]


这篇关于如何从数据库读取数据并存储到数组C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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