我有一个窗体,显示用户选择地理区域的组合框,然后根据选择设置SQL连接并执行SQL命令。用户总是很有可能无法访问SQL Server。我设置了一个try/catch,并向用户显示错误信息,但并不真正想要中断,我是VS C#的新手,并且正在寻求关于如何将控制传递给用户可以通过调整的一点的指导不同的选择。如何为登录失败处理SQL异常
将执行回传给表单加载是合理的吗?如果是的话,我该怎么做?如果不是,应该如何处理?
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
if (comboBox1.SelectedIndex > 0)
{
List<String> distinctTableList = AttributeMap.DistinctTablesList(comboBox1.SelectedItem.ToString());
lbTableNames.DataSource = distinctTableList;
}
}
public static List<String> DistinctTablesList(String environment)
{
List<String> tables = new List<string>();
var config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
AppSettingsSection appSettingSection = (AppSettingsSection)config.GetSection("cbSettings");
SqlConnection sqlcon = new SqlConnection(appSettingSection.Settings[environment].Value);
using (sqlcon)
{
StringBuilder errorMessages = new StringBuilder();
using (sqlcon)
{
try
{
sqlcon.Open();
}
catch (SqlException ex)
{
MessageBox.Show(ex.Message);
}
}
public partial class frmClassBuilder : Form
{
private List<AttributeMap> attributeMapList;
private CacheClassFactory cacheFactory;
public frmClassBuilder()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
List<String> environmentList = AttributeMap.EnvironmentList();
comboBox1.DataSource = environmentList;
}
=============================================================
using (sqlcon)
{
try
{
sqlcon.Open();
}
catch (SqlException ex)
{
MessageBox.Show(ex.Message);
}
}
向我们展示如何使用连接字符串实例化'sqlcon'?你是什么意思“我真的不想打破”?您可以在这里获得创意,如果没有太多的区域,您可以尝试环境列表中的所有值,并删除导致异常的条目,只留下组合框中用于用户选择的有效环境/连接字符串 - 这样它就不会中断。 – 2014-10-11 04:46:38