namespace ConnectionStringTesting
{
public partial class Form1 : Form
{
SPSite _site;
public Form1()
{
InitializeComponent();
CreateContext();
}
private void CreateContext()
{
_site = new SPSite("http://adfsaccount:2222/");
}
private void btnAdmin_Click(object sender, EventArgs e)
{
Config config = (Config)_site.WebApplication.GetChild<Config>("a5");
if (config == null)
{
txtConnectionString.Text = " Connection String is not set yet ";
}
else
{
txtConnectionString.Text = config.ConnectionString;
}
pnlAdmin.Visible = true;
}
private void btnOk_Click(object sender, EventArgs e)
{
Config config = (Config)_site.WebApplication.GetChild<Config>(" connectionstring ");
if (config == null)
{
config = new Config("connectionstring ", _site.WebApplication);
if (!string.IsNullOrEmpty(txtConnectionString.Text))
{
config.ConnectionString = txtConnectionString.Text;
}
else
{
config.ConnectionString = "Connection String Not set ";
}
config.Update();
MessageBox.Show("Connection String Got added ");
}
else
{
config.ConnectionString = txtConnectionString.Text.ToString();
config.Update();
MessageBox.Show("Connection String Got Updated");
}
pnlAdmin.Visible = false;
}
private void btnOperation_Click(object sender, EventArgs e)
{
Config config = (Config)_site.WebApplication.GetChild<Config>("connectionstring");
if (config == null)
{
MessageBox.Show("Connection String is Not set ");
}
else
{
txtConnectionString.Text = config.ConnectionString;
SqlConnection con = new SqlConnection(txtConnectionString.Text);
try
{
con.Open();
DataTable dt = new DataTable();
string strQuery = "select * from Person.Address";
SqlCommand cmd = new SqlCommand(strQuery, con);
cmd.CommandType = CommandType.Text;
SqlDataAdapter ada = new SqlDataAdapter();
ada.SelectCommand = cmd;
ada.Fill(dt);
dataGridView1.DataSource = dt;
pnlOperation.Visible = true;
}
catch (Exception ex)
{
MessageBox.Show("Connection String is not Correct!!! Go to Admin link and make it correct ");
}
}
}
private void btnOperationOK_Click(object sender, EventArgs e)
{
pnlOperation.Visible = false;
}
}
}
Conclusion
In this article, we saw How to configure connection string using SPPersistedObject. Thanks for reading.