Autocomplete comboBox that checks items in its list are entered - c#

Is there a way to check when an item is entered in a comboBox, is only one in which is actually in the list? To explain further, if anything outside the list is selected it won't accept that input. I've looked within stackoverflow but the only solution am seeing is that of changing my comboBox style to a dropdown list style. The problem with this is that there are more than a hundred records to select from so the autocomplete on the comboBox is absolutely necessary to filter these out by the user input entered.
Updated(declared matched globally):
private void comboBox3_TextChanged(object sender, EventArgs e)
{
ComboBox c = ((ComboBox)sender);
string[] items = c.Items.OfType<string>().ToArray();
matched = items.Any(i => i == c.Text.Trim().ToLower());
}
and this is where it executes:
private void button5_Click(object sender, EventArgs e)
{
if (matched==false)
{
MessageBox.Show("Value in Carimed Items does not exist");
}else
{
if (string.IsNullOrEmpty(comboBox5.Text))
{
MessageBox.Show("Please select output file to be written to!");
}
else
{
// int current = 0;
if (comboBox1.Text.Trim() == string.Empty)
{
MessageBox.Show("All fields must be filled in before saving!");
}
else
{
// StringBuilder csvconten = new StringBuilder();
// csvconten.AppendFormat("{0},{1},{2},{3},{4},{5}\r\n", comboBox2.Text, textBox5.Text, textBox2.Text, comboBox3.Text, textBox3.Text, comboBox1.Text);
// string csvpath = "cross_check.csv";
// File.AppendAllText(csvpath, csvconten.ToString());
string connectionString3 = "Data Source=LPMSW09000012JD\\SQLEXPRESS;Initial Catalog=Pharmacy_Output_File;Integrated Security=True";
string query3 = "INSERT INTO dbo.[" + comboBox5.Text + "] VALUES('" + comboBox2.Text + "','" + textBox5.Text.Replace("'", "''") + "','" + textBox7.Text.Replace("'", "''") + "','" + textBox2.Text.Replace("'", "''") + "','" + comboBox3.Text.Replace("'", "''") + "','" + textBox3.Text + "','" + comboBox1.Text + "');";
using (SqlConnection connection = new SqlConnection(connectionString3))
{
SqlCommand command = new SqlCommand(query3, connection);
command.Connection.Open();
command.ExecuteNonQuery();
command.Connection.Close();
}
// textBox1.Clear();
// textBox3.Clear();
// comboBox3.ResetText();
textBox2.Clear();
textBox3.Clear();
comboBox3.ResetText();
comboBox1.ResetText();
}
string connectionString2 = "Data Source=LPMSW09000012JD\\SQLEXPRESS;Initial Catalog=Pharmacies;Integrated Security=True";
string query2 = "UPDATE Liguanea_Lane2 SET Progress= '1' where code = '" + comboBox2.Text + "'; ";
using (SqlConnection connection = new SqlConnection(connectionString2))
{
SqlCommand command = new SqlCommand(query2, connection);
command.Connection.Open();
command.ExecuteNonQuery();
}
//this.liguanea_ProgressTableAdapter1.Fill(this.pharmaciesDataSet7.Liguanea_Progress);
comboBox2.SelectedIndex = comboBox2.SelectedIndex + 1;
//current = liguaneaLane2BindingSource.Position;
//this.liguanea_Lane2TableAdapter.Fill(this.pharmaciesDataSet3.Liguanea_Lane2);
refreshDataGrid2();
if (dataGridView1.CurrentRow != null)
{
dataGridView1.CurrentCell =
dataGridView1
.Rows[Math.Min(dataGridView1.CurrentRow.Index + 1, dataGridView1.Rows.Count - 1)]
.Cells[dataGridView1.CurrentCell.ColumnIndex];
// liguaneaLane2BindingSource.Position = Math.Min(current + 1, liguaneaLane2BindingSource.Count - 1);
}
}
}
}

You can Use the TextChanged Event of the ComboBox to See if the enter text exsists in you list:
private void comboBox1_TextChanged(object sender, EventArgs e)
{
ComboBox c = ((ComboBox)sender);
string[] items = c.Items.OfType<string>().ToArray();
bool matched = items.Any(i => i == c.Text.Trim().ToLower());
}
You can declare the matched bool globally in the form that TextChanged event would assign its value then you can use it in other Methods like:
void Button_Click(object sender, e EventArgs){
if(matched)
{
//do something
} else{
// show an error message
}
}

Related

Dropdown List Select index Default if no User Input

I have a dropdown list which works fine if the user selects one of the 6 options.
However if no action is taken because the first Option is the one required the selected value stays blank.
I have tried to set default selected value and search other solutions via Stack Overflow. Code Project, etc. but nothing works.
it may be something basic in my code!
static string prevPage = String.Empty;
protected void Page_Load(object sender, EventArgs e)
{
FileUpload1.Attributes["multiple"] = "multiple";
txtUN.Text = Request.QueryString["SVCCNo"];
lblid.Text = Session["username"].ToString();
txtCID.Text = Request.QueryString["CID"];
lblCID.Text = Request.QueryString["CID"];
lblSeparator.Text = " - ";
lblLocation.Text = Request.QueryString["LName"];
lblAssetName.Text = Request.QueryString["SVCCIDName"];
if (!IsPostBack)
{
prevPage = Request.UrlReferrer.ToString();
}
}
protected void Upload(object sender, EventArgs e)
{
string conn = ConfigurationManager.ConnectionStrings["SVCCAssetsDb"].ConnectionString;
SqlConnection sqlcon = new SqlConnection(conn);
sqlcon.Open();
//lblType.Text = "1";
for (int i = 0; i < Request.Files.Count; i++)
{
//move lbl inside loop
int uniquenuumber = Convert.ToInt32(txtUN.Text);
HttpPostedFile postedFile = Request.Files[i];
if (postedFile.ContentLength > 0)
{
//lblType.Text = txtType.Text;
int txttype = 1;
txttype = Convert.ToInt32(lblType.Text);
string userid = lblid.Text;
string fileName = Path.GetFileName(postedFile.FileName);
postedFile.SaveAs(Server.MapPath("~/Attachment/") + fileName);
lblMessage.Text += string.Format("<b>{0}</b> uploaded.<br />", fileName);
string sqlquery = "INSERT INTO Attachment (UserName, FilePath, UniqueNumber, TypeCode) VALUES ('" + userid + "', + '" + fileName + "', + '" + uniquenuumber + "', '" + txttype + "')";
SqlCommand sqlcmd = new SqlCommand(sqlquery, sqlcon);
sqlcmd.ExecuteNonQuery();
}
}
sqlcon.Close();
}
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
var selectedValue = ((DropDownList)sender).SelectedValue;
if (!string.IsNullOrEmpty(txtType.Text))
txtType.Text = selectedValue;
lblType.Text = txtType.Text;
}
protected void btnReturn_Click(object sender, EventArgs e)
{
Response.Redirect(prevPage);
}
}
aspx code:
Multi-File Upload
Files Must be All of the Same Type e.g. Photographs
Select the File Type Before Selecting the Files to Upload
Otherwise Files Chosen will be Clear Cleared
From what I guess without having the front code :
You're having a problem with this line :
int txttype = 1;
txttype = Convert.ToInt32(lblType.Text);
Which is caused because if you don't select another item from your dropdown, your label isn't updated and so this create a problem ?
If that's the case (else just explain me where I'm wrong )
You could just do a first intialisation of your label Type at the page load (in the !Page.IsPostBack Condition !!)
lblType.Text = "Your Default value as string";
Indeed, the select index changed event will trigger only if you change the dropdown, which in the case, if you stay on the first item, will not be triggered.
But there's maybe something else, let's try that first ! :)
SOLVED! Just a matter of getting the Code Rejigged.
Code Now Reads:
string conn =
ConfigurationManager.ConnectionStrings["SVCCAssetsDb"].ConnectionString;
SqlConnection sqlcon = new SqlConnection(conn);
sqlcon.Open();
int txttype = Convert.ToInt32(lblType.Text);
for (int i = 0; i < Request.Files.Count; i++)
{
//move lbl inside loop
int uniquenuumber = Convert.ToInt32(txtUN.Text);
HttpPostedFile postedFile = Request.Files[i];
if (postedFile.ContentLength > 0)
{
//lblType.Text = txtType.Text;
//int txttype = 1;
txttype = Convert.ToInt32(lblType.Text);
string userid = lblid.Text;
string fileName = Path.GetFileName(postedFile.FileName);
postedFile.SaveAs(Server.MapPath("~/Attachment/") + fileName);
lblMessage.Text += string.Format("<b>{0}</b> uploaded.<br />",
fileName);
string sqlquery = "INSERT INTO Attachment (UserName, FilePath,
UniqueNumber, TypeCode) VALUES ('" + userid + "', + '" + fileName + "', + '" +
uniquenuumber + "', '" + txttype + "')";
SqlCommand sqlcmd = new SqlCommand(sqlquery, sqlcon);
sqlcmd.ExecuteNonQuery();
}
}
sqlcon.Close();
}
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
var selectedValue = ((DropDownList)sender).SelectedValue;
if (!string.IsNullOrEmpty(txtType.Text))
txtType.Text = selectedValue;
lblType.Text = selectedValue;
}

how to convert value stored in session as an integer

I am trying to save data into my database using the value stored in a session, however, the value must be of type int as stated in the database. how do I go about doing this? the code for the insertion is below.
protected void btnSave_outcome_Click(object sender, EventArgs e)
{
if (con.State == ConnectionState.Closed)
con.Open();
SqlCommand sqlCmd = new SqlCommand("OutcomeCreateOrUpdate", con);
sqlCmd.CommandType = CommandType.StoredProcedure;
sqlCmd.Parameters.AddWithValue("#outcomeID", (hfoutcomeID.Value == "" ? 0 : Convert.ToInt32(hfoutcomeID.Value)));
sqlCmd.Parameters.AddWithValue("#learning_activity", (ddlActivity.SelectedValue.Trim()));
sqlCmd.Parameters.AddWithValue("#objectiveID", int.Parse(Session["objectiveID"].ToString()));
sqlCmd.Parameters.AddWithValue("#audience", (txtAudience1.Text.Trim()));
sqlCmd.Parameters.AddWithValue("#condition", (txtCondition1.Text.Trim()));
sqlCmd.Parameters.AddWithValue("#bloom_level", (ddlCategory1.SelectedValue.Trim()));
sqlCmd.Parameters.AddWithValue("#verb", (ddlVerb1.SelectedValue.Trim()));
sqlCmd.Parameters.AddWithValue("#product", (txtProduct2.Text.Trim()));
sqlCmd.Parameters.AddWithValue("#degree", (txtDegree1.Text.Trim()));
sqlCmd.Parameters.AddWithValue("#statement", ("Given " + txtCondition1.Text.Trim() + ", " + txtAudience1.Text.Trim() + " Will be able to " + ddlVerb1.SelectedItem.Text + " " + txtProduct2.Text.Trim()+ " " + txtDegree1.Text.Trim() +"."));
//sqlCmd.Parameters.AddWithValue("#moduleID", (ddlmodules.SelectedIndex));
sqlCmd.ExecuteNonQuery();
con.Close();
//string objectiveID = hfobjectiveID.Value;
string outcomeID = hfoutcomeID.Value;
Clear();
if (outcomeID == "")
lblSuccessMessage.Text = "Saved Successfully";
else
lblSuccessMessage.Text = "Updated Successfully";
//FillGridView(); for outcomes
new_outcome.Visible = true;
}
and I created the session as follows
protected void redirect_outcomes_Click(object sender, EventArgs e)
{
Session["objectiveID"] = objectiveID.ToString();
//Session["module"] = ddlmodules.SelectedValue;
//Response.Redirect("learningoutcomes.aspx?MultiView1.ActiveIndex=" +2);
final_objective1.Text = "Given " + txtCondition.Text.Trim() + ", " + txtAudience.Text.Trim() + " Will be able to " + txtVerb.Text.Trim() + " " + txtProduct.Text.Trim() + " .";
MultiView1.Visible = false;
GoToAudience1.Visible = false;
MultiView2.ActiveViewIndex = 0;
}
Your code:-
sqlCmd.Parameters.AddWithValue("#objectiveID", int.Parse(Session["objectiveID"].ToString()));
My suggestion:-
if(Session["objectiveID"] != null)
{
sqlCmd.Parameters.AddWithValue("#objectiveID", Convert.ToInt32(Session["objectiveID"]));
}
No need to use try parse/parse because you are storing only integer value in session. So session have either empty or integer value.

Change calendar day back color

I'm trying to save a day data from calendar and change it color to red after click on it . so the saved on in database will be in red color and unsaved will be in green color .
The problem is when i choose multiple days just the last one will change to red the previous one will stuck in green color .
The data is received from sql correctly i show it in text box and all saved days is appear
int[] arr;
dynamic ad;
protected void Page_Load(object sender, EventArgs e)
{
cn.Open();
SqlCommand c1 = new SqlCommand("select count(*) from app1", cn);
int count = int.Parse(c1.ExecuteScalar().ToString());
cn.Close();
arr = new int[count];
DataClassesDataContext db = new DataClassesDataContext();
ad =(from a in db.app1s select a.data).ToArray();
}
protected void Button1_Click(object sender, EventArgs e)
{
//id is int
SqlCommand cmd = new SqlCommand("insert into app1 values('" + TextBox1.Text + "','" + TextBox2.Text + "','" + TextBox3.Text + "','" + TextBox4.Text + "','" + TextBox5.Text + "','" + DropDownList1.SelectedValue + "')", cn);
cn.Open();
cmd.ExecuteNonQuery();
cn.Close();
}
protected void Calendar1_SelectionChanged(object sender, EventArgs e)
{
foreach (var item in ad)
{
if (int.Parse(item) == int.Parse(Calendar1.SelectedDate.Day.ToString()))
{
Calendar1.SelectedDayStyle.BackColor = System.Drawing.Color.Red;
}
else
{
Calendar1.SelectedDayStyle.BackColor = System.Drawing.Color.Green;
TextBox5.Text = Calendar1.SelectedDate.Day.ToString();
}
}
}
I try to use array but same problem
int[] arr;
protected void Page_Load(object sender, EventArgs e)
{
cn.Open();
SqlCommand c1 = new SqlCommand("select count(*) from apoyt1", cn);
int count = int.Parse(c1.ExecuteScalar().ToString());
cn.Close();
arr = new int[count + 1];
for (int i = 1; i <= count; i++)
{
cn.Open();
SqlCommand cm = new SqlCommand("select data from apoyt1 where id='" + i + "'", cn);
arr[i] = int.Parse(cm.ExecuteScalar().ToString());
cn.Close();
}
}
protected void Button1_Click(object sender, EventArgs e)
{
//id is int
SqlCommand cmd = new SqlCommand("insert into apoyt1 values('" + TextBox1.Text + "','" + TextBox2.Text + "','" + TextBox3.Text + "','" + TextBox4.Text + "','" + TextBox5.Text + "','" + DropDownList1.SelectedValue + "')", cn);
cn.Open();
cmd.ExecuteNonQuery();
cn.Close();
}
protected void Calendar1_SelectionChanged(object sender, EventArgs e)
{
for (int i = 0; i < arr.Length; i++)
{
if (arr[i] == int.Parse(Calendar1.SelectedDate.Day.ToString()))
{
Calendar1.SelectedDayStyle.BackColor = System.Drawing.Color.Red;
}
else {
Calendar1.SelectedDayStyle.BackColor = System.Drawing.Color.Green;
TextBox5.Text = Calendar1.SelectedDate.Day.ToString();
}
}
}
Your code is not doing the purpose that it should planed for, as well Calendar1.SelectedDayStyle.BackColor is always referring to same selected object. so try the following:
1) create a list for days, as number of days are unknown.
List<Int32> days;
protected void Page_Load(object sender, EventArgs e)
{
}
2) Because of each time the page is reloading you need to store these days in a session.
protected void Calendar1_SelectionChanged(object sender, EventArgs e)
{
days = (List<int>)Session["var"];
if (days == null) days = new List<int>();
days.Add(Calendar1.SelectedDate.Day);
Session["var"] = days;
ListBox1.Items.Clear();
foreach (int d in days)
{
Calendar1.SelectedDates.Add(new DateTime(Calendar1.SelectedDate.Year, Calendar1.SelectedDate.Month, d));
Calendar1.SelectedDayStyle.BackColor = System.Drawing.Color.Red;
ListBox1.Items.Add(d.ToString());
}
}
3) i have uploaded a sample of code so you can check it Here

CheckBox Not Sending Checked Value to Access Database C# Asp

This is my C# code and my issue as the title says is my checkbox values are not going into my access database, or at least not changing them.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Configuration;
using System.Data;
using System.Data.OleDb;
using System.Data.SqlClient;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
}
Label1.Text = (string)Session["sesionicontrol"];
}
protected void txtPass_TextChanged(object sender, EventArgs e)
{
}
protected void check1_SelectedIndexChanged(object sender, EventArgs e)
{
}
protected void btnLogin_Click(object sender, EventArgs e)
{
//Declare Variables
string username = txtEmailLogin.Text;
string password = txtPasswordLogin.Text;
username = username.Trim().ToLower();
password = password.Trim().ToLower();
//Handle null or empty fields
if ((string.IsNullOrEmpty(username)) || (string.IsNullOrEmpty(password)))
{
lblError.Text = "Please Enter a vaild Username or Password";
}
else if (((username.Contains("#mu.edu") || (username.Contains("#marquette.edu")))))
{
//Run select query and populate a table, then check to see if the user and pass are in that table
OleDbConnection conn = null;
DataTable dt = new DataTable();
try
{
string connString =
ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
conn = new OleDbConnection(connString);
string query = "Select Count(*) From Team Member Where Email = ? AND Pass = ?";
OleDbCommand cmd = new OleDbCommand(query, conn);
conn.Open();
cmd.CommandType = CommandType.Text;
OleDbDataAdapter da = new OleDbDataAdapter(cmd);
da.Fill(dt);
}
catch (Exception ex)
{
// handle error here
}
finally
{
conn.Close();
}
//checking if there is a result in the virtual table, if there is they successfully logged in
if (dt.Rows.Count >= 0)
{
lblError.Text = "Welcome!";
/// Take to Homepage
CommonClass.txtEmail = txtEmailLogin.Text;
Server.Transfer("HomePage.aspx", true);
}
else
{
lblError.Text = "Incorrect Username or Password";
}
}
}
protected void btnRegister_Click(object sender, EventArgs e)
{
OleDbConnection conn = null;
DataTable gridTable = new DataTable();
try
{
string connString = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
conn = new OleDbConnection(connString);
string query = "INSERT INTO [Team Member] (FirstName, LastName, Email, Pass, Age, Hobbies, FavoriteColor, Major) VALUES('" + txtFirst.Text + "','" + txtLast.Text + "', '" + txtEmail.Text + "','" + txtPass.Text + "','" + txtAge.Text + "','" + txtHobbies.Text + "', '" + txtFavorite.Text + "','" + txtMajor.Text + "')";
string query1 = "INSERT INTO [Team Member] (Soccer, Basketball, Football, Softball) VALUES('" + c1.Checked.ToString() + "', '" + c2.Checked.ToString() + "', '" + c3.Checked.ToString() + "', '" + c4.Checked.ToString() + "')";
OleDbCommand cmd = new OleDbCommand(query, conn);
conn.Open();
cmd.CommandType = CommandType.Text;
cmd.ExecuteNonQuery();
cmd.Dispose();
lblError1.Text = ("Registered Successfully");
}
catch (Exception ex)
{
lblError1.Text = ("Error occurred: " + ex.Message);
}
finally
{
conn.Close();
}
}
protected void btnReg_Click(object sender, EventArgs e)
{
txtFirst.Visible = !txtFirst.Visible;
txtLast.Visible = !txtLast.Visible;
txtEmail.Visible = !txtEmail.Visible;
txtPass.Visible = !txtPass.Visible;
txtPassConfirm.Visible = !txtPassConfirm.Visible;
btnRegister.Visible = !btnRegister.Visible;
btnReg.Visible = !btnReg.Visible;
c1.Visible = !c1.Visible;
c2.Visible = !c2.Visible;
c3.Visible = !c3.Visible;
c4.Visible = !c4.Visible;
txtAge.Visible = !txtAge.Visible;
txtHobbies.Visible = !txtHobbies.Visible;
txtFavorite.Visible = !txtFavorite.Visible;
txtMajor.Visible = !txtMajor.Visible;
lbl1.Text = "Sports you want to play";
lbl2.Text = "Age";
lbl3.Text = "Hobbies";
lbl4.Text = "Favorite Color";
lbl5.Text = "Major";
}
protected void c2_SelectedIndexChanged(object sender, EventArgs e)
{
}
protected void c1_CheckedChanged(object sender, EventArgs e)
{
}
}
My database looks like this
If you are appending to Access Yes/No fields then I would try removing the single quotes (') from the second INSERT INTO line:
string query1 = "INSERT INTO [Team Member]
(Soccer, Basketball, Football, Softball)
VALUES(" + c1.Checked.ToString() + ", "
+ c2.Checked.ToString() + ", "
+ c3.Checked.ToString() + ", "
+ c4.Checked.ToString() + ")";
First, The reason your check box values never get inserted is because your OleDbCommand is defined like this:
OleDbCommand cmd = new OleDbCommand(query, conn);
Using query as the command.text. query1 is never referenced to this and thus never executes.
Second (more important), you need to have the insert statement as one statement, not 2. Calling 2 Insert statements would cause 2 rows to added to the table. One containing values from query, and one containing the checkbox value from query1. You should define your query in one string like this
string query = "INSERT INTO [Team Member] " +
"(FirstName, LastName, Email, Pass, Age, Hobbies, FavoriteColor, Major, Soccer, Basketball, Football, Softball) " +
"VALUES('" + txtFirst.Text + "','" + txtLast.Text + "', '" + txtEmail.Text + "','" + txtPass.Text + "','" +
txtAge.Text + "','" + txtHobbies.Text + "', '" + txtFavorite.Text + "','" + txtMajor.Text + "','" +
c1.Checked.ToString() + "', '" + c2.Checked.ToString() + "', '" + c3.Checked.ToString() + "', '" + c4.Checked.ToString() + "')";

Data gets Truncated from database

I am designing a Window based application in C# using VS2010 and SqlServer2008-r2. I am
using a service Based Database(.mdf),in it there is a table having four fields, if i Store
data in the table and close the application and re-run the application the data gets Lost.
Why so and how to get rid of it.
I am Using Following routine for saving
private void Save(object sender, EventArgs e)
{
Program.connection.Close();
bool k = srchpreventry();
try
{
if (k)
{
string query = " update orderform set Enrolment_Expected = " + textBox2.Text + ", Stock_on_Hand=" + textBox3.Text + ", Number_Required = "+ textBox4.Text + " where Name = '" + textBox1.Text + "';";
SqlCommand cmd = new SqlCommand(query, Program.connection);
cmd.ExecuteNonQuery();
Program.connection.Close();
}
else
{
// Program.connection.Open();
string query = "insert into orderform(Name,Enrolment_Expected,Stock_on_Hand,Number_Required) values('" + textBox1.Text + "', '" + textBox2.Text + "', ' " + textBox3.Text + "',' " + textBox4.Text + "')";
SqlCommand cmd = new SqlCommand(query, Program.connection);
cmd.ExecuteNonQuery();
Program.connection.Close();
}
}
catch (Exception ae)
{
string str = ae.ToString();
MessageBox.Show(str);
}
finally
{
textBox1.Text = "";
textBox2.Text = "";
textBox3.Text = "";
textBox4.Text = "";
textBox1.Enabled = false;
textBox2.Enabled = false;
textBox3.Enabled = false;
textBox4.Enabled = false;
Program.connection.Close();
}
}
public bool srchpreventry()
{
Program.connection.Open();
string query = " Select name from orderform where Name = '" + textBox1.Text + "';";
SqlCommand cmd = new SqlCommand(query, Program.connection);
SqlDataReader dtr = cmd.ExecuteReader();
if (dtr.Read() == true)
{
dtr.Close();
return true;
}
else
{
dtr.Close();
return false;
}
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
Program.connection.Close();
Program.connection.Open();
string query = " Select * from orderform where Name = '" + textBox1.Text + "';";
SqlCommand cmd = new SqlCommand(query, Program.connection);
SqlDataReader dtr = cmd.ExecuteReader();
if (dtr.Read() == true)
{
textBox2.Text = dtr[1].ToString();
textBox3.Text = dtr[2].ToString();//GetString(2);
textBox4.Text = dtr[3].ToString();
}
else
{
textBox2.Text = "";
textBox3.Text = "";
textBox4.Text = "";
}
}
public static SqlConnection connection = null;
static string appath = Library_Records.Program.app_path;
string connectionstring = string.Format(#"Data Source=.\SQLEXPRESS;AttachDbFilename={0};Integrated Security=True;User Instance=True", appath);
static string dbfiles = null;
internal static string app_path
{
get { return dbfiles = "|Datadirectory|\\records.mdf"; }
}
/*******************datagrid code********************/
Program.connection.Open();
string query = "select * from orderform";
SqlDataAdapter MyDA = new SqlDataAdapter();
MyDA.SelectCommand = new SqlCommand(query, Program.connection);
DataTable table = new DataTable();
MyDA.Fill(table);
BindingSource bSource = new BindingSource();
bSource.DataSource = table;
dataGridView1.DataSource = bSource;
Check to see if you can increase the characters allowed in the column for example nvarchar(max) cause now it could be nvarchar(200) - this is just an example
In Visual Studio?
You are not by chane having VIsual Studio load the same empty database again every time you start debug?
and close the application and re-run the application the data gets Lost.
Either someone ignores errors that get thrown on insert, does not commit a transaction or tvisal studio just ocpies the same rdatabase template into the directory every time you start.
I strongly (emphasis on strongly) suggest that you start using stored procedures (either in code or in the database), but besides that.. you don't start a transaction or something similar?
Or post the Program.Connection class code into the question.

Categories

Resources