注册 登录
编程论坛 C# 论坛

c#连接数据库出错

lukebc 发布于 2016-08-24 16:32, 2624 次点击
using System;
using System.Collections.Generic;
using
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;

namespace WindowsFormsApplication3
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            if (textBox1.Text == "")
            {
                MessageBox.Show("请输入名称");
                else
                {
                    try
                    {
                        string constr="server=;database="+textBox1.Text.Trim()+";uid=sa;pwd=";
                        SqlConnection conn=new SqlConnection(constr);
                        conn.Open();
                        if(conn.State==ConnectionState.Open)
                        {
                        label1.Text="["+textBox1.Text.Trim()+"]已经连接打开";
                        }
                }

                        catch
                    {
                           MessageBox.Show("数据库打开失败");
                        }
         }
        }
    }
    }
}

错误    1    只有 assignment、call、increment、decrement 和 new 对象表达式可用作语句   
错误    2    无效的表达式项“else"

错误    3 提示 else处要输入分号

我现在不知道怎么改,望哪位高手帮我
3 回复
#2
over12302016-08-24 17:04
if (textBox1.Text == "")
            {
                MessageBox.Show("请输入名称");
            }
            else
            {
                try
                {
                    string constr = "server=;database=" + textBox1.Text.Trim() + ";uid=sa;pwd=";
                    SqlConnection conn = new SqlConnection(constr);
                    conn.Open();
                    if (conn.State == ConnectionState.Open)
                    {
                        label1.Text = "[" + textBox1.Text.Trim() + "]已经连接打开";
                    }
                }

                catch
                {
                    MessageBox.Show("数据库打开失败");
                }
            }
#3
redmarss2016-09-01 11:30
if没结束就套else?
#4
彷徨人生迷茫2016-09-01 22:51
if  else .........
1