private bool DoesUserHavePermission() { try { SqlClientPermission clientPermission = new SqlClientPermission(PermissionState.Unrestricted); // will throw an error if user does not have permissions clientPermission.Demand(); return true; } catch { return false; } } private void GetNames() { if (!DoesUserHavePermission()) return; lbNames.Items.Clear(); // You must stop the dependency before starting a new one. // You must start the dependency when creating a new one. SqlDependency.Stop(connectionString); SqlDependency.Start(connectionString); using (SqlConnection cn = new SqlConnection(connectionString)) { using (SqlCommand cmd = cn.CreateCommand()) { cmd.CommandType = CommandType.Text; cmd.CommandText = "SELECT FirstName, LastName FROM dbo.[Users]"; cmd.Notification = null; // creates a new dependency for the SqlCommand SqlDependency dep = new SqlDependency(cmd); // creates an event handler for the notification of data // changes in the database. // NOTE: the following code uses the normal .Net capitalization methods, though // the forum software seems to change it to lowercase letters dep.OnChange += new OnChangeEventHandler(dep_onchange); cn.Open(); using (SqlDataReader dr = cmd.ExecuteReader()) { while (dr.Read()) { lbNames.Items.Add(dr.GetString(0) + " " + dr.GetString(1)); } } } } } void dep_onchange(object sender, SqlNotificationEventArgs e) { // this event is run asynchronously so you will need to invoke to run on UI thread(if required). ISynchronizeInvoke i = (ISynchronizeInvoke)this; if (i.InvokeRequired) lbNames.BeginInvoke(new MethodInvoker(GetNames)); else GetNames(); // this will remove the event handler since the dependency is only for a single notification SqlDependency dep = sender as SqlDependency; // NOTE: the following code uses the normal .Net capitalization methods, though // the forum software seems to change it to lowercase letters dep.OnChange -= new OnChangeEventHandler(dep_onchange); } private void Form1_FormClosing(object sender, FormClosingEventArgs e) { SqlDependency.Stop(connectionString); } private void Form1_Load(object sender, EventArgs e) { GetNames(); button1.Enabled = DoesUserHavePermission(); } // button to show other form with textboxes to insert data into database private void btnShowForm_Click(object sender, EventArgs e) { Form2 f = new Form2(); f.Show(); }
var
This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)