The ConnectionString is already a string. You don't need to call the ToString() on top of it. The following piece of code is enough.
string restoreConnStr = ConfigurationManager.ConnectionStrings["DBCon"].ConnectionString;
The piece ListBox1.SelectedValue is too buggy. The user can not select any values in the listbox and still press the button. not even select and press restore. I think there is a count object in the Selected items collection that should be used extensively.
Like,
if (ListBox1.SelectedItems.Count > 0)
{
string tableName = ListBox1.SelectedValue;
}
else
{
MessageBox.Show("Please select a value");
ListBox1.Focus();
}
Thirdly, check for the tables count , before you hard card values such as "Tables[0]". I would instead recommend using Typed Datasets for safety. and place all your code inside that check condition.
using (DataSet dSet = new DataSet())
{
dSet.ReadXml(Server.MapPath("~/backup/" + tableName + ".xml"));
if (dSet.Tables.Count > 0)
{
foreach (DataRow row in dSet.Tables[0].Rows)
{
dSetBackup.Tables[0].NewRow();
dSetBackup.Tables[0].Rows.Add(row.ItemArray);
}
//Create a command builder to update dSetBackup DataSet
SqlCommandBuilder cmd = new SqlCommandBuilder(dAd);
//Following update command will push all added rows of dSetBackup DataSet into the //database
dAd.Update(dSetBackup, tableName); // We are done !!!
}
else
{
MessageBox.Show("We are not done yet !!!");
}
}
And lastly, i would show the "Message" Property of the exception , instead of the Exception.ToString();
catch (Exception ex)
{
lblMessage.Text = ex.Message;
}