RichTextBox.RTF not accepting String generated from Database - C# - c#

I have a bit of a weird problem here. I'm attempting to create a form that, when making a selection from a ListBox, will poll data from a database and display it in a RichTextBox. I need the data to be in RTF for formatting purposes.
It works fine if I do something like this:
private void SaveListTest_SelectedIndexChanged(object sender, EventArgs e)
{
DescriptionName = Convert.ToString(SaveListTest.SelectedItem);
//CallDescriptionTest();
CallDescriptionTest2();
SaveRichTest.Rtf = DescriptionText;
}
public void CallDescriptionTest2()
{
switch (DescriptionName)
{
case "Test":
DescriptionText = #"{\rtf1\ansi\ Test}";
break;
case "Words":
DescriptionText = #"{\rtf1\ansi\ A really long phrase}";
break;
}
}
In such a case, the RichTextBox (SaveRichTest) will take the data and display it just fine.
However, if I do something like this, where the Description column in the database has the text entered exactly as above (ex - #"{\rtf1\ansi\ Test}"):
private void SaveListTest_SelectedIndexChanged(object sender, EventArgs e)
{
DescriptionName = Convert.ToString(SaveListTest.SelectedItem);
CallDescriptionTest();
//CallDescriptionTest2();
SaveRichTest.Rtf = DescriptionText;
}
public void CallDescriptionTest()
{
using (SqlConnection con = new SqlConnection(BuildDB))
{
con.Open();
string sql = String.Format("Select * from Abilities where Name = '{0}'", DescriptionName);
SqlCommand oCmd = new SqlCommand(sql, con);
using (SqlDataReader oReader = oCmd.ExecuteReader())
{
while (oReader.Read())
{
DescriptionText = Convert.ToString(oReader["Description"]);
}
con.Close();
}
}
}
This will instead cause the program to crash, with an error that the "File format is not valid".
I know the text is pulling from the database correctly, because if I change "SaveRichTest.Rtf" to "SaveRichTest.Text", it displays it properly (albeit with the RTF formatting code displayed).
I just can't figure out why it won't take the string properly in the second case. It makes no sense to me whatsoever. Can someone help?

I guess in the case when you tried to show your output in plain text your output was: #"{\rtf1\ansi\ Test}
This would mean when you want to show this string formatted directly from the database you would pass it "#"{\rtf1\ansi\ Test}"" instead of the correct format. I'd suggest you store the format without the # in the database and simply show the result.

Related

Content Dialog does not display after database insert query - UWP App

I cannot get a UWP content dialog to display after executing a database insert query. Below is the code I have written. The Content dialog displays as it should when the insert query code is commented out. Am I missing something? Any help will be appreciated. Thanks
private async void Admin_Button_Click(object sender, RoutedEventArgs e)
{
String selItem = TaskCombo.SelectedValue.ToString();
dbDetail.AddAdminData(selItem, SettingTxt.Text);
Windows.UI.Xaml.Controls.ContentDialog infoDialog = new Windows.UI.Xaml.Controls.ContentDialog()
{
Title = "Alert",
Content = "Records entered successfully",
CloseButtonText = "OK"
};
Windows.UI.Xaml.Controls.ContentDialogResult result = await infoDialog.ShowAsync();
}
Try to define String selItem as property like this String selItem{set;get;}=TaskCombo.SelectedValue.ToString();
The problem was an open data reader associated with the connection that was open and needed to be closed first. The db query was executing successfully, however the content dialogue could not be display because of the open data reader.

Fill ComboBox on form in a method triggered by a button

First of all, if I click a button the method cbBefüllen will execute.
private void btnEntfernen_Click(object sender, EventArgs e)
{
FeiertageEntfernen entfernen = new FeiertageEntfernen();
entfernen.cbBefüllen();
entfernen.Show();
entfernen.Focus();
}
The following method is just here as an interface between my form and a class. (Please don't ask, in my code I have some good reasons for it ;) ).
public void cbBefüllen()
{
database.cbFeiertagebefüllen();
}
The method cbFeiertagebefüllen (tries to) fills my ComboBox, which is located in the form "feiertagentfernen".
public void cbFeiertagebefüllen()
{
FeiertageEntfernen feiertagentfernen = new FeiertageEntfernen();
string Query = #"select bezeichnung from feiertage";
using (var command = new SQLiteCommand(Query, sqlite_conn))
{
if (sqlite_conn.State != ConnectionState.Open)
{
sqlite_conn.Open();
}
using (var reader = command.ExecuteReader())
{
while (reader.Read())
{
string übergabe = reader.GetString(0);
feiertagentfernen.cbFeiertag.Items.Add(übergabe);
}
}
}
}
But after this whole process my ComboBox is still empty. The reader in the last picture picks the correct value from the database, but somehow it won't write it into the ComboBox.
Your problem is in this line:
FeiertageEntfernen feiertagentfernen = new FeiertageEntfernen();
in your cbFeiertagebefüllen()
You make a new form but you want your combo box from the form from the 1st piece of code to be filled. To fix this you could pass along an instance of the form to the filling method.
The updated 2 pieces of code will be (first piece can be left alone):
In cbBefullen:
database.cbFeiertagebefüllen(this);
//'this' means we're passing along the form as parameter
In cbFeiertagebefüllen:
public void cbFeiertagebefüllen(FeiertageEntfernen feiertagentfernen)
{
string Query = #"select bezeichnung from feiertage";
using (var command = new SQLiteCommand(Query, sqlite_conn))
{
if (sqlite_conn.State != ConnectionState.Open)
{
sqlite_conn.Open();
}
using (var reader = command.ExecuteReader())
{
while (reader.Read())
{
string übergabe = reader.GetString(0);
feiertagentfernen.cbFeiertag.Items.Add(übergabe);
}
}
}
}
The FeiertageEntfernen form instance on which you're filling the cbFeiertag combo box in cbFeiertagebefüllen() is not the form's instance you're showing after that. You need to pass the entfernen instance to cbFeiertagebefüllen():
public void cbBefüllen()
{
database.cbFeiertagebefüllen(this);
}
public void cbFeiertagebefüllen(FeiertageEntfernen feiertagentfernen)
{
// Use the passed in instance instead of a newly created one
//FeiertageEntfernen feiertagentfernen = new FeiertageEntfernen();
string Query = #"select bezeichnung from feiertage";
// ....................
}
For this to work, the ComboBox which you need to fill, should be globally declared, i.e. outside the scope of your functions. The rest is probably fine. Also it's better if you get the values you need to display in the comboBox to the main form rather than calling the ComboBox instance 2 levels deeper.
I know this is a little confusing, in simple words, What you could do is, fill the values(descriptions of the holidays) from the DataBase into a list. Make your functions return this list when called. And finally where the ComboBox is declared, you could just add that list as the source of the ComboBox
It looks like you are adding the options to the combo box, but you are not actually setting the selected item.
To do so, you need to set cbFeiertag.SelectedIndex or cbFeiertag.SelectedValue.

How do I prevent button code from running twice if the user clicks more than once in C#?

I have a method where, when the user clicks a button, it selects data from a table and adds it to a text box. The problem is that when a user clicks 2 or more times, the display code runs once for each click and the data is displayed multiple times in the text box.
How can I clear the Text box and display the data only once?
Note: One of the Text boxes by default has a string which I use on a query that gets the data. When I clear the data, the query throws an error since it doesn't have that string I just cleared to finish the query.
This is the code method that I'm using:
private void FillFilds()
{
mycon.Open();
string queryfill= "SELECT *From master where Num=#Num";
oleDbCmd = new OleDbCommand(queryfill, mycon);
oleDbCmd.Parameters.Add("#Lot", OleDbType.VarChar, 40).Value = Numtxt.Text;
OleDbDataReader reader;
try
{
reader = oleDbCmd.ExecuteReader();
reader.Read();
Idlbl.Text += reader[0];
Datetxt.Text += reader[1];
DatePtxt.Value = Convert.ToDateTime(reader[2]);
Jobtxt.Text += reader[3];
NoBtxt.Text += reader[4];
NoPatxt.Text += reader[5];
NoMtxt.Text += reader[6];
Numtxt.Text += reader[7];
NoRtxt.Text += reader[8];
Description.Text += reader[9];
NoMatxt.Text += reader[10];
reader.Close();
}
catch (Exception error)
{
MessageBox.Show(error.ToString());
}
mycon.Close();
}
I think this might clear some questions...
sorry im new at writing in forums.
You could store this default value somewhere, for example as field in the class:
private string DefaultNumber = "12345";
// ...
Then you can assign this value to the TextBox:
Number.Text = DefaultNumber; // instead of Number.Clear() or Number.Text = ""
But you should really use sql-parameters to prevent sql-injection:
string queryfill = "SELECT * From master where Number = #Number";
DataTable table = new DataTable();
using (OleDbConnection conn = new OleDbConnection(ConnString))
using (OleDbDataAdapter da = new OleDbDataAdapter(queryfill, conn))
{
da.SelectCommand.Parameters.AddWithValue("Number", Number.Text);
da.Fill(table);
}
If the text is showing up multiple times in the text box, then you must be appending it rather than setting it. Make sure that you set the .Text value of the textbox using the = sign rather than appending to whatever is there (such as with +=).
You may also want to consider hard coding your default rather than relying on it being displayed in a text box. You can check if the text box is empty or not. If it is empty, then you can use the default, if it is not empty, you can use the entered value. Use String.IsNullOrEmpty(textbox.Text) to check if the string is empty.
You should also note that your code is completely insecure and would allow someone to do anything they wanted with your database through an attack called SQL Injection. You should never allow user input to be passed directly in to a SQL statement. Instead, you should use parameterized SQL and pass the user input as a parameter. This prevents a hacker from being able to insert additional SQL commands in to the input. For example, in this case, if I put '); DROP TABLE Master; SELECT * FROM passwords(' in your textbox, it would destroy your master table.

"Input string was not in a correct format."

I am working on a project in which I have a form through which I can edit a question available in a list view. Whenever I select a row from the list view and click on the 'modify' button, the text boxes above the list view load the question and its options.
This means that when I select a row in the list view and click on the 'modify' button, the question loads itself into the text boxes. I edit the question there and click on 'save' to save changes, but I am not able to access the data in the text boxes. It says {"Input string was not in a correct format."}.
My code of the form frmFormWizard's 'edit' button is given below:
frmFormWizard.cs Code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.Sql;
using System.Data.SqlClient;
namespace SurveyBuilder
{
public partial class frmFormWizard : Form
{
int intPanelNumber = 1;
Boolean blnCancel = false;
//int intFlag = 1;
public frmFormWizard()
{
InitializeComponent();
}
...
private void btnEditTwoOrMoreOptions_Click(object sender, EventArgs e)
{
int QuestionID;
string sql;
QuestionID = Convert.ToInt32(lvTwoOrMoreOptions.SelectedItems[0].Text.ToString());
{
SqlConnection cn = new SqlConnection();
SqlCommand rs = new SqlCommand();
SqlDataReader sdr = null;
clsConnection clsCon = new clsConnection();
clsCon.fnc_ConnectToDB(ref cn);
sql = "";
sql += "SELECT * FROM SurveyQuestionLog WHERE SurveyQuestionLog.QuestionLogID = "+ QuestionID +"";
//sql += "SELECT * FROM SurveyQuestionLog";
rs.Connection = cn;
rs.CommandText = sql;
sdr = rs.ExecuteReader();
while (sdr.Read())
{
txtTwoOrMoreQuestions.Text = (string)sdr["Question"];
txtOption1.Text = (string)sdr["Choice1"];
...
}
sdr.Close();
rs = null;
cn.Close();
}
}
Whenever I try to compile the code it says "{"Input string was not in a correct format."}" and this error is shown on the following line:
QuestionID = Convert.ToInt32(lvTwoOrMoreOptions.SelectedItems[0].Text.ToString());
Please let me know what I am doing wrong.
It looks like some space include in the text.
Use
lvTwoOrMoreOptions.SelectedItems[0].Text.ToString().Trim()
and convert to int32.
hope this code will solve you
From comments
if your ListView is in report mode (i.e. it looks like a grid) then you will need the SubItems property. lvTwoOrMoreOptions.SelectedItems gets you each items in the list view - SubItems gets you the columns. So lvTwoOrMoreOptions.SelectedItems[0].SubItems[0] is the first column value,
Please change your code like below.
int QuestionID;
bool IsIntValue = Int32.TryParse("YOUR-VARIABLE", out QuestionID);
if (IsIntValue)
{
// YOUR CODE HERE
}
Hope i will be help.
whenever i try to compile the code it says "{"Input string was not in a correct format."}"
This error won't come on compiling.
Now the error comese because you are trying to parse an invalid string to integer. To do it in a safe manner, you should do it like this
int questionID;
if(int.TryParse(vTwoOrMoreOptions.SelectedItems[0].Text.ToString(),out questionID))
{
//success code
}
else
{
//failure code
}
You might be trying to access a control inside a control, maybe a GridView or DetailsView.
Try using something like this:
empsalary = Convert.ToInt32(((TextBox)DetailsView1.Rows[1].Cells[1].Controls[0]).Text);
It looks that whatever that text is containing some characters which cannot be converted to integer like space, letters, special characters etc. Check what is coming through dropdown as below
lvTwoOrMoreOptions.SelectedItems[0].Text.ToString();
and see if that is the case.

display formatted data from database to richtextbox

I made a program that can add formatted (change font,size and colour) data using a richtextbox into my MS Access Database, there is also a normal text box to store the topics which is loaded to a listbox when you click on a topic in the listbox it is supposed to display the formatted text in another richtextbox, it displays the plain text perfectly but as soon as a topic is clicked with formatted text it displays how the text was formatted:
{\rtf\ansi\ansicpg 1252\deflang7177{\f0\fnil\fcharset 0 Microsoft Sans serif;}}
{\colortbl;\red0\green255\blue128;}
\viewkind4\uc 1\pard\cf1\fs17 now\cf0\par
}
My code:
private void listItem_SelectedIndexChanged(object sender, EventArgs e)
{
string connstring = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Temp\SumWizz.accdb";
OleDbConnection conn = new OleDbConnection(connstring);
string query = "SELECT * FROM Items WHERE Name = '" + listItem.Text + "'";
OleDbCommand cmd = new OleDbCommand(query, conn);
OleDbDataReader reader;
try
{
conn.Open();
reader = cmd.ExecuteReader();
// reads the data and fills the combo box and listbox
while (reader.Read())
{
string Sdetail = reader.GetString(2);
richItem.Text = Sdetail;
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
conn.Close();
}
I have changed richItem (my richtextbox) to richItem.rtf = Sdetail;
Then it displays the formatted text perfectly but when topic selected with plain text it says format invalid, I have to use it in 2 more places. is there a check I can do to first check if the text has rtf properties or any other way to get it to display both plain and formatted text?
Rich text seems to always starts with {\rtf (I may be wrong. But it seems like a fair assumption). So it you check for that, you'll be able to decide.
Please see this link for a convenient extension method to do this.
Code from msdn forum
/// <summary>
/// Returns the DataFormat string of the text.
/// </summary>
/// <param name="text">Text to check.</param>
/// <returns>Value from the <see cref="DataFormats"/> enumeration.</returns>
public static string GetDataFormat(this string text)
{
// First validate the text
if (string.IsNullOrEmpty(text)) return System.Windows.DataFormats.Text;
// Return right data
if (text.StartsWith(#"{\rtf")) return System.Windows.DataFormats.Rtf;
// Return default
return System.Windows.DataFormats.Text;
}
Usage:
var format = myString.GetDataFormat();
if (format == System.Windows.DataFormats.Rtf)
{
// process RTF text
}
else
{
// process plain text
}

Categories

Resources