I have this problem, i search the DB and return results which i turn into links and print them but with the way i have chosen "Response.Write();" i get the results printed at the upper left corner, which sucks cause it messes up my whole page... :(
Is there a way i can print at a specific location (under the search bar preferably) and keep the results as links ?
Thanks in advance!
protected void Button1_Click1(object sender, EventArgs e)
{
DataTable PassRecord = new DataTable();
String str = "select First_Name,Email_Account,Surname,id from ID where (First_Name like '%'+ #search +'%' ) OR (Surname like '%'+ #search +'%') OR (Email_Account like '%'+ #search +'%')";
SqlCommand Srch = new SqlCommand(str, con);
Srch.Parameters.Add("#search", SqlDbType.NVarChar).Value = TextBox1.Text;
if (TextBox1.Text != "")
{
con.Open();
Srch.ExecuteNonQuery();
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = Srch;
DataTable dt = new DataTable();
DataTable dtResult = new DataTable();
da.Fill(dt);
PID = (int)(Session["id"]);
int SaveTheFirst = PID;
foreach (DataRow dr in dt.Rows)
{
PID2 = dr["id"].ToString() ;
if (PID.ToString() != PID2 )
{
counter++;
var field = "<a href='" + Page.ResolveUrl("~/PageView.aspx?Email=" + dr["id"].ToString()) + "'>" + (dr["First_Name"] + "").ToString() + "</a>";
Response.Write(field);
HttpContext context = HttpContext.Current;
Response.Write("<br/>");
}
}
con.Close();
}
else
{
string display = " Not Valid Search Criteria!";
ClientScript.RegisterStartupScript(this.GetType(), "myalert", "alert('" + display + "');", true);
}
}
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));
I have a form that when I select a column name from a ComboBox, and type in a text box it filters and displays the searched criteria in the DataGridView. When I search for "Reference" which is an int data type, which is also identity, and primary key. I get the error message :
"Cannot perform 'Like' operation on System.Int32 and System.String."
My code is
DataTable dt;
private void searchForm_Load(object sender, EventArgs e)
{
SqlCeConnection con = new SqlCeConnection(#"Data Source=|DataDirectory|\LWADataBase.sdf;");
SqlCeDataAdapter sda = new SqlCeDataAdapter("select * from customersTBL", con);
dt = new DataTable();
sda.Fill(dt);
dataGridView1.DataSource = dt;
comboSearch.Items.Add("[Reference]");
comboSearch.Items.Add("[First Name]");
comboSearch.Items.Add("[Surename]");
comboSearch.Items.Add("[Address Line 1]");
comboSearch.Items.Add("[Address Line 2]");
comboSearch.Items.Add("[County]");
comboSearch.Items.Add("[Post Code]");
comboSearch.Items.Add("[Contact Number]");
comboSearch.Items.Add("[Email Address]");
}
private void searchTxt_TextChanged(object sender, EventArgs e)
{
if (comboSearch.SelectedItem == null)
{
searchTxt.ReadOnly = true;
MessageBox.Show("Please select a search criteria");
}
else
{
searchTxt.ReadOnly = false;
DataView dv = new DataView(dt);
dv.RowFilter = "" + comboSearch.Text.Trim() + "like '%" + searchTxt.Text.Trim() + "%'";
dataGridView1.DataSource = dv;
}
}
Convert the number to a string inside the filter:
dv.RowFilter = string.Format("CONVERT({0}, System.String) like '%{1}%'",
comboSearch.Text.Trim(), searchTxt.Text.Trim());
Try this perhaps?
dv.RowFilter = "'%" + comboSearch.Text.Trim() + "%' like '%" + searchTxt.Text.Trim() + "%'";
It may just be a missing quotation, because the query reads as
" 123 like '%123%' "
the code tried to search from gridview (devexpress)..
DataRow[] dr = dt.Select("invoiceId ='" + Convert.ToInt32(gridView1.GetRowCellValue(id, "invoiceId")) + "' AND '%" + Convert.ToDouble(gridView1.GetRowCellValue(id, "Amount_Paid")) + "%' LIKE '%" + Convert.ToDouble(gridView1.GetRowCellValue(id, "Amount")) + "%' ");
if (dr.Length > 0)
{
MessageBox.Show("already paid");
}
I am new to C# and I want to do this ASAP as I've had this problem since past week. I have tried a few approaches and not yet gotten the correct output. Here is my code:
private void btnDelete_Click(object sender, EventArgs e)
{
try
{
String itemcode = tbItemCode.Text.ToString();
String shade = tbShade.Text.ToString();
String rollnumber = tbRollNumber.Text.ToString();
System.Data.OleDb.OleDbConnection conn = new System.Data.OleDb.OleDbConnection(#"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Users\Eranga\Documents\Visual Studio 2010\Projects\RollAllocationModel\RollAllocationModel\Roll.mdb;Persist Security Info=True;Jet OLEDB:Database Password=admin");
String deletequery = "DELETE FROM TabRoll WHERE (ItemCode = '" + itemcode + "') AND (Shade = '" + shade + "') AND (RollNumber = '" + rollnumber + "')";
//String deletequery = "SELECT * FROM TabRoll";
//code by query builder ----> DELETE FROM TabRoll WHERE (ItemCode = '" + itemcode + "') AND (Shade = '" + shade + "') AND (RollNumber = '" + length + "');
conn.Open();
OleDbDataAdapter da = new OleDbDataAdapter(deletequery, conn);
OleDbCommandBuilder cb = new OleDbCommandBuilder(da);
DataTable dt = new DataTable();
da.Fill(dt);
BindingSource bSource = new BindingSource();
bSource.DataSource = dt;
dataGridView1.EndEdit();
bSource.EndEdit();
da.Update(dt);
dataGridView1.DataSource = bSource;
conn.Close();
MessageBox.Show("Data deleted");
}
catch (Exception exceptionObj)
{
MessageBox.Show(exceptionObj.Message.ToString());
}
}
Why doesn't the DataGrid does not update with the new record.
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())
I'm trying to export a SQL-Server query to an XML file now and I want to import that file to Access. I don't understand how to do this.
Here is the code I use to generate the XML:
protected void Button1_Click(object sender, EventArgs e) {
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["SqlSconn"].ConnectionString);
con.Open();
string strSQL = "select * from dbo.table_"+test.Text.ToString()+"";
SqlDataAdapter dt = new SqlDataAdapter(strSQL, con);
DataSet ds = new DataSet();
dt.Fill(ds, "" + test.Text.ToString() + "");
ds.WriteXml(Server.MapPath("temp.xml"));
}
This may be a start.
static void SaveToMDB(DataSet ds, string strMDBFile)
{
OleDbConnection cAccess = new OleDbConnection(
"Provider=Microsoft.Jet.OLEDB.4.0;Data source=" + strMDBFile);
cAccess.Open();
foreach (DataTable oTable in ds.Tables)
{
OleDbCommand oCommand = new OleDbCommand(
"DROP TABLE [" + oTable.TableName + "]", cAccess);
try
{
oCommand.ExecuteNonQuery();
}
catch (Exception) { }
string strCreateColumns = "";
string strColumnList = "";
string strQuestionList = "";
foreach (DataColumn oColumn in oTable.Columns)
{
strCreateColumns += "[" + oColumn.ColumnName + "] VarChar(255), ";
strColumnList += "[" + oColumn.ColumnName + "],";
strQuestionList += "?,";
}
strCreateColumns = strCreateColumns.Remove(strCreateColumns.Length - 2);
strColumnList = strColumnList.Remove(strColumnList.Length - 1);
strQuestionList = strQuestionList.Remove(strQuestionList.Length - 1);
oCommand = new OleDbCommand("CREATE TABLE [" + oTable.TableName
+ "] (" + strCreateColumns + ")", cAccess);
oCommand.ExecuteNonQuery();
OleDbDataAdapter da = new OleDbDataAdapter(
"SELECT * FROM [" + oTable.TableName + "]", cAccess);
da.MissingSchemaAction = MissingSchemaAction.Add;
da.FillLoadOption = LoadOption.OverwriteChanges;
da.InsertCommand = new OleDbCommand(
"INSERT INTO [" + oTable.TableName + "] (" + strColumnList
+ ") VALUES (" + strQuestionList + ")", cAccess);
foreach (DataColumn oColumn in oTable.Columns)
{
da.InsertCommand.Parameters.Add(
oColumn.ColumnName,
OleDbType.VarChar,
255,
oColumn.ColumnName
);
}
foreach (DataRow oRow in oTable.Rows)
oRow.SetAdded();
da.Update(oTable);
}
}
This Data will work only with ID and Name, using the system :
using System;using System.Collections.Generic;using System.Linq;using System.Web;using System.Web.UI;using System.Web.UI.WebControls;using System.Data.Sql;using System.Data.SqlClient;using System.Configuration;using System.Data;using System.IO;
using System.Xml.Linq;
//import SelectiveDatabaseBackup.xml to test9 table
string connectionString = ConfigurationManager.ConnectionStrings["ApplicationServices3"].ConnectionString;
SqlConnection sqlConnection1 = new SqlConnection(connectionString);
SqlCommand cmd = new SqlCommand();
cmd.CommandType = CommandType.Text;
DataSet ds = new DataSet();
ds.ReadXml(XDocument.Load("c:/d/SelectiveDatabaseBackup.xml").CreateReader());
foreach (DataTable table in ds.Tables)
{
//Create table
foreach (DataRow row in table.Rows)
{
string name = row[1].ToString();
string id = row[0].ToString();
cmd.CommandText = "INSERT test9 VALUES ('"+ id +"','"+ name + "')";
cmd.Connection = sqlConnection1;
sqlConnection1.Open();
cmd.ExecuteNonQuery();
sqlConnection1.Close();
}
}
//--------------------------