this is my sample code to check the data on Table1 using 2 filters, column1 and between data in column2. The code I have is working but is only getting 1 result. So for example. I enter "1" in textbox1, "3" in textbox2 and "6" in textbox3. Select * from TABLE1 where COLUMN1 = '1' AND COLUMN2 BETWEEN '3' AND '6' -- when run in sql result is 3,4,5,6 but in C# I am only getting "6". Can you help me with this to get "3,4,5,6" as a result. Thank you.
public partial class WebForm1 : System.Web.UI.Page
{
SqlConnection SC;
SqlCommand CMD;
SqlDataReader DR;
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
SC = new SqlConnection(ConfigurationManager.ConnectionStrings["BABBLER"].ConnectionString);
SC.Open();
CMD = new SqlCommand("Select * from TABLE1 WHERE COLUMN1= '" + TextBox1.Text + "' and COLUMN2 Between '" + TextBox2.Text + "'" + " and " + "'" + TextBox3.Text + "'", SC);
DR = CMD.ExecuteReader();
if (DR.HasRows)
{
while (DR.Read())
{
label1.Text = DR["COLUMN2"].ToString();
}
}
}
}
}
Your loop is not appending the values, rather overwriting Label1. Change your while loop to
while (DR.Read())
{
label1.Text += DR["COLUMN2"].ToString() + ",";
}
if (label1.Text.EndsWith(",")) label1.Text = label1.Text.SubString(0, label1.Text.Length-1) //Remove the last comma
Change
label1.Text = DR["COLUMN2"].ToString();
as
label1.Text = label1.Text +", " + DR["COLUMN2"].ToString();
if (Label1.Text.Length > 2)
Label1.Text = Label1.Text.Substring(2);
try this code
SC = new SqlConnection(ConfigurationManager.ConnectionStrings["BABBLER"].ConnectionString);
SC.Open();
CMD = new SqlCommand("Select * from TABLE1 WHERE COLUMN1= '" + TextBox1.Text + "' and COLUMN2 Between '" + TextBox2.Text + "'" + " and " + "'" + TextBox3.Text + "'", SC);
DataSet ds = new DataSet();
SqlDataAdapter da = new SqlDataAdapter(CMD);
da.Fill(ds);
string data="";
for (int i = 0; i < ds.Tables[0].Rows.Count; i++ )
{
if(data=="")
{
label1.Text = ds.Tables[0].Rows[i]["COLUMN2"].ToString();
}
else
{
label1.Text +=","+ ds.Tables[0].Rows[i]["COLUMN2"].ToString();
}
}
There are a number of methods to combine results into a comma-separated list. However, using string concatenation should not be one - concatenating strings is slow, especially if you might have a large number of results. Try one of the following instead:
Using a StringBuilder
StringBuilder sb = new StringBuilder();
boolean doneFirstRow = false;
while (DR.READ())
{
if (doneFirstRow)
{
sb.Append(", ");
}
else
{
doneFirstRow = true;
}
sb.Append(dr["COLUMN2"].ToString());
}
Label1.Text = sb.ToString();
Using a List with String.Join:
List<string> values = new List<string>();
while (DR.READ())
{
values.Add(dr["COLUMN2"].ToString());
}
Label1.Text = String.Join(", ", values);
NB: If not using NET4.5 you'll need String.Join(", ", values.ToArray())
Related
I want to show my datatable value into text box with including headers
I tried something like this not sure its correct or not ?
private void Button16_Click(object sender, EventArgs e)
{
textBox5.Text = string.Empty;
if (checkedListBox1.CheckedItems.Count > 0)
{
string strSQLConn = "Server =" + textBox1.Text + "; Initial Catalog =" + textBox2.Text + "; User ID =" + textBox3.Text + "; Password = " + textBox4.Text + ";";
SqlConnection SQLConn = new SqlConnection(strSQLConn);
SQLConn.Open();
foreach (var item in checkedListBox1.CheckedItems)
{
DataRowView row = item as DataRowView;
SqlCommand SQLCmd = new SqlCommand("select TABLE_NAME, COLUMN_NAME, DATA_TYPE, CHARACTER_MAXIMUM_LENGTH, IS_NULLABLE from INFORMATION_SCHEMA.COLUMNS where TABLE_NAME = '" + row["Table_Name"] + "' ", SQLConn);
SQLCmd.CommandType = CommandType.Text;
SqlDataAdapter Da = new SqlDataAdapter(SQLCmd);
DataTable dt = new DataTable();
Da.Fill(dt);
if (dt.Rows.Count > 0)
{
textBox5.Text = dt.Rows[0]["TABLE_NAME"].ToString();
textBox5.Text = dt.Rows[0]["COLUMN_NAME"].ToString();
textBox5.Text = dt.Rows[0]["DATA_TYPE"].ToString();
textBox5.Text = dt.Rows[0]["CHARACTER_MAXIMUM_LENGTH"].ToString();
textBox5.Text = dt.Rows[0]["IS_NULLABLE"].ToString();
}
}
}
I believe you are trying to append instead of overriding the text. Therefore,
textBox5.Text = dt.Rows[0]["TABLE_NAME"].ToString() + ", ";
textBox5.Text += dt.Rows[0]["COLUMN_NAME"].ToString()+ ", ";
textBox5.Text += dt.Rows[0]["DATA_TYPE"].ToString()+ ", ";
textBox5.Text += dt.Rows[0]["CHARACTER_MAXIMUM_LENGTH"].ToString()+ ", ";
textBox5.Text += dt.Rows[0]["IS_NULLABLE"].ToString();
To go through all rows
for (int i = 0; i < dt.Rows.Count; i++)
{
textBox5.Text = dt.Rows[i]["TABLE_NAME"].ToString() + ", ";
textBox5.Text += dt.Rows[i]["COLUMN_NAME"].ToString()+ ", ";
textBox5.Text += dt.Rows[i]["DATA_TYPE"].ToString()+ ", ";
textBox5.Text += dt.Rows[i]["CHARACTER_MAXIMUM_LENGTH"].ToString()+ ", ";
textBox5.Text += dt.Rows[i]["IS_NULLABLE"].ToString();
}
Moreover, I suggest to scope your connection, command and adapter in using(so system can close/dispose them automatically) and use
SqlParameter instead of string concatenation(to prevent potential SQL injection)
using (SqlConnection SQLConn = new SqlConnection(strSQLConn))
{
SQLConn.Open();
foreach (var item in checkedListBox1.CheckedItems)
{
DataRowView row = item as DataRowView;
using (SqlCommand SQLCmd = new SqlCommand("select TABLE_NAME, COLUMN_NAME, DATA_TYPE, CHARACTER_MAXIMUM_LENGTH, IS_NULLABLE from INFORMATION_SCHEMA.COLUMNS where TABLE_NAME = #tableName ", SQLConn))
{
SQLCmd.Parameters.AddWithValue("tableName", row["Table_Name"]);
using (SqlDataAdapter Da = new SqlDataAdapter(SQLCmd))
{
DataTable dt = new DataTable();
Da.Fill(dt);
// rest of the code
}
}
}
}
You can retrieve columns from DataTable.Columns and if you too want to attach to the TextBox then sample as below
textBox5.Text += string.Join(",", dt.Columns.OfType<DataColumn>().Select(col => col.ColumnName));
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
}
}
In gridview that am try to displaying the data in the database but it is ignoring the first row from the tabel & taking the rest of row.., plz suggest me what to do..
below is my code.
protected void Page_Load(object sender, EventArgs e)
{
DBLibrary obj = new DBLibrary();
String Parent = (string)Session["parentName"];
String ss = "Select StudentId from Tbl_Parents where parentName='" + Parent + "'";
SqlDataReader dr6 = obj.ExecuteReader(ss);
dr6.Read();
string id = dr6[0].ToString();
string bind = "SELECT AnuFeeMaster.StudentId, Tbl_Student.SName, AnuFeeMaster.Month, AnuFeeMaster.Year, AnuFeeMaster.FeeAmount, " +
" AnuFeeMaster.PaidAmount FROM AnuFeeMaster INNER JOIN Tbl_Student ON AnuFeeMaster.StudentId = Tbl_Student.StudentId where ( AnuFeeMaster.StudentId ='" + id + "')";//and (AnuFeeMaster.ChkDate='" + date.ToString() + "') ";
SqlDataReader dr = obj.ExecuteReader(bind);
dr.Read();
gv1.DataSource = dr;
gv1.DataBind();
}
Remove the dr.Read(); line.
You are passing the reader already advanced with one position.
I have a button on my Gridview:
<asp:Button ID="lnk_ship" runat="server" CssClass="btn-mini" Text="Ship Software" />
I am loading my Gridview from SQL, to a Class, then a DataBind() event,
protected void FilterResults(object sender, EventArgs e)
{
var shipments = new List<SoftShipments>();
DateTime dt1 = Convert.ToDateTime(Textbox1.Text);
DateTime dt2 = Convert.ToDateTime(Textbox2.Text);
string cvt1 = "'" + dt1.Year.ToString() + "-" + dt1.Month.ToString() + "-" + dt1.Day.ToString() + "'";
string cvt2 = "'" + dt2.Year.ToString() + "-" + dt2.Month.ToString() + "-" + dt2.Day.ToString() + "'";
string qry = null;
if (Showshipped.Checked)
{
qry = "select * from sft_Ship where sft_Entry_Dt between " + cvt1 + " and " + cvt2;
}
else {
qry = "select * from sft_Ship where sft_Entry_Dt between " + cvt1 + " and " + cvt2 + " and sft_shipped = 'No'";
}
SqlConnection conn = new SqlConnection(Sitecore.Configuration.Settings.GetConnectionString("softship"));
conn.Open();
SqlCommand cmd = new SqlCommand(qry, conn);
DataSet ds = new DataSet();
SqlDataAdapter da = new SqlDataAdapter(cmd);
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
shipments.Add(new SoftShipments() { index = (int) dr["id"], softtitle = dr["sft_SoftTitle"].ToString(),
productID = dr["sft_ProductID"].ToString(), ver = dr["sft_Version"].ToString(),
custnam = dr["sft_CustName"].ToString(), title = dr["sft_Title"].ToString(),
comp = dr["sft_Company"].ToString(), shipAddr = dr["sft_ShipAddress"].ToString(),
dept = dr["sft_Dept"].ToString(), city = dr["sft_City"].ToString(), state = dr["sft_State"]
.ToString(), postalCd = dr["sft_PostalCd"].ToString(), country = dr["sft_Country"].ToString(),
email = dr["sft_Email"].ToString(), entry_date = dr["sft_Entry_Dt"].ToString(),
ship_date = dr["sft_Ship_Dt"].ToString(), shipped = dr["sft_Shipped"].ToString()
});
}
gdv_Ship.DataSource = shipments;
gdv_Ship.DataBind();
conn.Close();
}
I would like to load the Gridview with the button visible if the value "shipped = 'No' or not visible if 'Yes' ... just not quite certain where to add this code? Any assistance would be appreciated.
Regards,
You could subscribe to the databound event of the grid, and then show/hide the buttons in the template with a FindControl("controlName")
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.