C# (WPF) 中显示整个表从 mysql

发布时间: 2016/12/29 23:06:47
注意事项: 本文中文内容可能为机器翻译,如要查看英文原文请点击上面连接.

我想了很长时间,但我不能做它。

我有这个简单的 XAML:

<Window ....>
    <Grid>
        <Button x:Name="tlacitko" Content="Button" HorizontalAlignment="Left" Height="38" Margin="343,259,0,0" VerticalAlignment="Top" Width="149" Click="Button_Click"/>
        <TextBlock x:Name="vypisBlock" HorizontalAlignment="Left" Height="188" Margin="32,25,0,0" TextWrapping="Wrap" Text="" VerticalAlignment="Top" Width="442"/>

    </Grid>
</Window>

和这.cs

.. usings ..

namespace Pokus
{
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            string cs = @"server=localhost;userid=root;
            password=vertrigo;database=vzkaznik";

            MySqlConnection conn = null;
            MySqlDataReader rdr = null;

            try
            {
                conn = new MySqlConnection(cs);
                conn.Open();

                string stm = "SELECT * FROM elsvo_zpravy";
                MySqlCommand cmd = new MySqlCommand(stm, conn);
                rdr = cmd.ExecuteReader();

                while (rdr.Read())
                {
                  string vypis = ""; 
                  vypis += (rdr.GetInt32(0) + " - " + rdr.GetString(1) + " - " + rdr.GetString(2) + " - " + rdr.GetString(3) + "\n");
                  vypisBlock.Text = vypis;
                }


            }
            catch (MySqlException ex)
            {
                string chyba = "Error: {0}" + ex.ToString(); // doplnit (if = cislo chyby -> hlaska) místo šílenosti co to zobrazuje ted
                vypisBlock.Text = chyba;

            }

        }

    }
}

我想要应用程序表明整个表的内容现在只有最后一行。

我是如何做的?

谢谢

解决方法 1:

你覆盖您的结果不断在 while 循环。

StringBuilder vypis = ""; 
while (rdr.Read())
{
 vypis.AppendLine(string.Format("{0} - {1} - {2} - {3}",
       rdr.GetInt32(0),
       rdr.GetString(1),
       rdr.GetString(2),
       rdr.GetString(3));    
}
vypisBlock.Text = vypis.ToString();
赞助商