Two days ago, I published a sample, which illustrates how to merge data from an MS SQL Server database into a template, using TX Text Control .NET for Windows Forms. Feedback on this blog post shows that many users are storing documents in a database and not on a file system.
Today, I would like to publish a sample project, which shows how to use TX Text Control as a bound control to load and save documents from and to a Microsoft SQL Server database.
This sample uses the standard .NET database components to connect to the database:
- BindingNavigator
The BindingNavigator helps to navigate through the records.
- BindingSource
The BindingSource is connected to the database that contains the documents.
- DataSet
The created DataSet is the in-memory cache of data retrieved from the data source.
- TableAdapter
The TableAdapter provides communication between the application and the database.
All of these components are created automatically using the Visual Studio database wizards. We just need to connect the BindingNavigator with the BindingSource and we are able to navigate through all records.
The sample database contains two columns: An ID and the document itself. The document is stored as an RTF document in a VARCHAR(MAX) column, but you can save all other supported formats as well.
The complete loading and saving happens in the CurrentChanged event of the BindingSource. This event is exposed when the user navigates through the records or creates a new entry. The following code shows how the document is saved automatically when the user navigates to another document and how the current document is loaded into TX Text Control.
// [C#] private DataRowView curView; private void bindingSource1_CurrentChanged(object sender, EventArgs e) { try { // curView is the last visible document // store curView when user navigates to the next document if (curView != null) { string data; textControl1.Save(out data, TXTextControl.StringStreamType.RichTextFormat); curView["doc"] = data; // update the database documentsTableAdapter.Update(docsDataSet); } // get the new selected data row DataRowView curRow = (DataRowView)bindingSource1.Current; // check whether the selected document is a new document // and add an unique id if (curRow["id"].Equals(DBNull.Value)) { curRow["id"] = bindingSource1.Count; textControl1.ResetContents(); curView = curRow; } else { // load the current document into TX Text Control curView = curRow; textControl1.Load(curRow["doc"].ToString(), TXTextControl.StringStreamType.RichTextFormat); } } catch (Exception exc) { statusBar1.Text = exc.Message; } }
As a minimum, you need a TX Text Control .NET for Windows Forms 15.1 trial version and a Microsoft SQL Express edition (2005 or 2008). Download the Visual Studio 2008 C# project here: