how to display data from sql database to textbox using C#.net
how to display data from sql database to textbox using C#.net
9 solutions
You can use this :
SqlConnection Conn = new SqlConnection(Connection_String); SqlCommand Comm1 = new SqlCommand(Command, Conn); Conn.Open(); SqlDataReader DR1 = Comm1.ExecuteReader(); if (DR1.Read()) { textBox.Text = DR1.GetValue(0).ToString(); } Conn.Close();another way :
SqlConnection Conn = new SqlConnection(Connection_String); SqlCommand Comm1 = new SqlCommand(Command, Conn); Conn.Open(); textBox.Text = Comm1.ExecuteScalar(); Conn.Close();
Comments
Hello sir,
I was using my way,but i made a slight change according to you,even though it is not retriving.
I created in windows application,one form in that i had created three labels (first,middle,last) & infront of that i created textboxes with Search button in bottom .And now i created in database three fields called first,middle,last also i gave values for those fields . what i need is wen i enter in "first" textbox and hit the button search,for the remaining textboxs like middle & last the data has to be retrived into it.Now its giving error saying cannot convert varchar to int.I had given datatype as for all the fields in database as "varchar(50)". This is the error Conversion failed when converting the varchar value 'f' to data type int..
And this the code:
namespace Config_admin
{
public partial class Form2 : Form
{
SqlCommand cmd = new SqlCommand();
SqlDataReader rdr;
DataSet ds;
SqlDataAdapter da;
public Form2()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection("Data Source=CBP\\SQLEXPRESS;Initial Catalog=ECG;Integrated Security=True");
con.Open();
cmd.CommandText = "select * from Table2 where first=" + textBox1.Text.Trim();
cmd.Connection = con;
rdr = cmd.ExecuteReader();
bool temp = false;
while (rdr.Read())
{
//textBox1.Text = rdr.GetString(0);
textBox2.Text = rdr.GetString(1);
textBox3.Text = rdr.GetString(2);
//textBox4.Text = rdr.GetString(3);
//textBox5.Text = rdr.GetString(4);
//textBox6.Text = rdr.GetString(5);
//textBox7.Text = rdr.GetString(6);
//textBox8.Text = rdr.GetString(7);
//textBox9.Text = rdr.GetString(8);
//textBox10.Text = rdr.GetString(9);
temp = true;
}
if (temp == false)
MessageBox.Show("not found");
con.Close();
con.Open();
ds = new DataSet();
da = new SqlDataAdapter("select * from Table2", con);
da.Fill(ds, "Table2");
con.Close();
}
}
}
Please any one help me.
Thanks & Regards
Pradeep CBZ
pradeepcbckm@gmail.com
SqlConnection Conn = new SqlConnection(Connection_String);
SqlCommand Comm1 = new SqlCommand(Command, Conn);
Conn.Open();
SqlDataReader DR1 = Comm1.ExecuteReader();
if (DR1.Read())
{
textBox.Text = DR1.GetValue(0).ToString();
}
Conn.Close();
This code works fine
hii pradeep ,
change this line
cmd.CommandText = "select * from Table2 where first=" + textBox1.Text.Trim();
to
cmd.CommandText = "select * from Table2 where first='" + textBox1.Text.Trim()+"'";
it will work fine
thank you
yes ganesh its perfect now..thanks yar
this is so simple.don't do complicated program..........
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.SqlClient;
namespace RetrieveData
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
bool temp = false;
SqlConnection con = new SqlConnection("server=WASEEM\\SQLEXPRESS;database=malik;Trusted_Connection=True");
con.Open();
SqlCommand cmd = new SqlCommand("select * from Table2 where first='" + textBox1.Text.Trim() + "'", con);
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
textBox2.Text = dr.GetString(1);
textBox3.Text = dr.GetString(2);
temp = true;
}
if (temp == false)
MessageBox.Show("not found");
con.Close();
}
}
}
always welcome
Wonderful! Your solution is very helpful for me. Thanks very much!
For 3 layered, it's not correct solution, your data access and UI are in same layer :-(
dasdsa
1) Ensure your TextBox is MultiLine
2) Set up a connection to the database.
3) Set up an SQL command to read the numbers.
4) Clear the TextBox content.
5) Read the data from the DataBase and add each line to the TextBox.
An example of this is below, but bear in mind it will not work for you: your database and tables will be named differently, and you will need to get numbers and convert them to strings, instead of a string field called "message":
2) Set up a connection to the database.
3) Set up an SQL command to read the numbers.
4) Clear the TextBox content.
5) Read the data from the DataBase and add each line to the TextBox.
An example of this is below, but bear in mind it will not work for you: your database and tables will be named differently, and you will need to get numbers and convert them to strings, instead of a string field called "message":
string strConnect = @"Database=SMLogging;Data Source=GRIFFPC\SQLEXPRESS;Initial Catalog=SMLogging;Integrated Security=True"; using (SqlConnection con = new SqlConnection(strConnect)) { con.Open(); con.InfoMessage += new SqlInfoMessageEventHandler(con_InfoMessage); SqlDataReader r; using (SqlCommand com = new SqlCommand("SELECT * FROM SMAdmin.Log", con)) { r = com.ExecuteReader(); } List<string> lines = new List<string>(); while (r.Read()) { lines.Add((string) r["message"]); } myTextBox.Lines = lines.ToArray(); }
Solution 3
string strConnect = @"Database=SMLogging;Data Source=GRIFFPC\SQLEXPRESS;Initial Catalog=SMLogging;Integrated Security=True";
using (SqlConnection con = new SqlConnection(strConnect))
{
con.Open();
con.InfoMessage += new SqlInfoMessageEventHandler(con_InfoMessage);
}
SqlConnection Conn = new SqlConnection(Connection_String);
SqlCommand Comm1 = new SqlCommand(Command, Conn);
Conn.Open();
SqlDataReader DR1 = Comm1.ExecuteReader();
if (DR1.Read())
{
textBox.Text = DR1.GetValue(0).ToString();
}
Conn.Close();
There are two ways we can use Autocomplete feature
1. Auto complete textBox with previously entered text in textbox.
2. AutoComplete textBox by fetching the data from database.
1. Auto complete textBox with previously entered text in textbox.
For filling textbox with previously entered data/text in textbox using Autocomplete feature we can implement by setting autocomplete mode proeprty of textbox to suggest, append or sugestappend and setting autocomplete source to custom source progrmetically
First of all create a global AutoCompleteStringCollection and write code like this
2. AutoComplete textBox by fetching the data from database.
For this i've created a database with a table containing names which will be shown in textbox as suggestions, for this we need to create a AutoCompleteStringCollection and then add the records in this collection using datareader to fetch records from database
For autocomplete functionalty to work we need to define these 3 properties of textbox
1. AutoCompleteMode - we can choose either suggest or appned or suggestappend as names are self explanatory
2. AutoCompleteSource - this needs to be set as Custom Source
3. AutoCompleteCustomSource - this is the collection we created earlier
The complete C# code will look like this
1. Auto complete textBox with previously entered text in textbox.
2. AutoComplete textBox by fetching the data from database.
1. Auto complete textBox with previously entered text in textbox.
For filling textbox with previously entered data/text in textbox using Autocomplete feature we can implement by setting autocomplete mode proeprty of textbox to suggest, append or sugestappend and setting autocomplete source to custom source progrmetically
First of all create a global AutoCompleteStringCollection and write code like this
namespace WindowsApplication1 { public partial class Form1 : Form { AutoCompleteStringCollection autoComplete = new AutoCompleteStringCollection(); public Form1() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { autoComplete.Add(textBox1.Text); MessageBox.Show("hello"); } private void Form1_Load(object sender, EventArgs e) { textBox1.AutoCompleteMode = AutoCompleteMode.SuggestAppend; textBox1.AutoCompleteSource = AutoCompleteSource.CustomSource; //auto.Add(textBox1.Text); textBox1.AutoCompleteCustomSource = autoComplete; } } }
2. AutoComplete textBox by fetching the data from database.
For this i've created a database with a table containing names which will be shown in textbox as suggestions, for this we need to create a AutoCompleteStringCollection and then add the records in this collection using datareader to fetch records from database
For autocomplete functionalty to work we need to define these 3 properties of textbox
1. AutoCompleteMode - we can choose either suggest or appned or suggestappend as names are self explanatory
2. AutoCompleteSource - this needs to be set as Custom Source
3. AutoCompleteCustomSource - this is the collection we created earlier
The complete C# code will look like this
namespace AutoCompleteTextBox { public partial class frmAuto : Form { public string strConnection = ConfigurationManager.AppSettings["ConnString"]; AutoCompleteStringCollection namesCollection = new AutoCompleteStringCollection(); public frmAuto() { InitializeComponent(); } private void frmAuto_Load(object sender, EventArgs e) { SqlDataReader dReader; SqlConnection conn = new SqlConnection(); conn.ConnectionString = strConnection; SqlCommand cmd = new SqlCommand(); cmd.Connection = conn; cmd.CommandType = CommandType.Text; cmd.CommandText = "Select distinct [Name] from [Names]" + " order by [Name] asc"; conn.Open(); dReader = cmd.ExecuteReader(); if (dReader.HasRows == true) { while (dReader.Read()) namesCollection.Add(dReader["Name"].ToString()); } else { MessageBox.Show("Data not found"); } dReader.Close(); txtName.AutoCompleteMode = AutoCompleteMode.Suggest; txtName.AutoCompleteSource = AutoCompleteSource.CustomSource; txtName.AutoCompleteCustomSource = namesCollection; } private void btnCancel_Click(object sender, EventArgs e) { Application.Exit(); } private void btnOk_Click(object sender, EventArgs e) { MessageBox.Show("Hope you like this example"); } } }
Comments
plz solve this error
i have 1 textbox name is id.
using this id iwant to retrive the data from data base and display in other txtbox...?how is it possible....
and my code is given bellow
SqlConnection con2 = new SqlConnection();
con2.ConnectionString = "server=.;database=NOTES;uid=sa;pwd=sandip;";
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = new SqlCommand("SELECT Describstion,Title_name FROM notes WHERE id"=textBox1.Text, con2);
con2.Open();
da.Fill(ds);
// da.InsertCommand.ExecuteNonQuery();
textBox3.Text = ds.GetObjectData.ToString();
con2.Close();
da.Fill(ds);
What is ds?
SqlConnection con = new SqlConnection(Connection_String);
SqlCommand cmd = new SqlCommand(Command, Conn);
Conn.Open();
SqlDataReader dr = Comm1.ExecuteReader();
cmd.CommandText="Select * from tabelname";
dr=cmd.executereader();
textbox1.text=dr[0];
On DATA LAYER
Create Object of datalayer
Lets Name Of DL Be Customer
Create Object of BL Class
SqlConnection Conn = new SqlConnection(Connection_String);
public int GetNo()
{
Conn.Open();
SqlCommand Cmd = new SqlCommand(Command, Conn);
SqlDataReader dr= Cmd.ExecuteReader();
Int64 intNo;
while(dr.read())
{
intNo=int64.parse(dr.getValue(0).tostring);
}
Conn.Close();
}
ON BUSINESS LAYERCreate Object of datalayer
Lets Name Of DL Be Customer
CustomerDL ObjCustDL=new CustomerDL();
public int GetNo()
{
int Result;
result=objCustDL.GetNo();
return Result;
}
ON .CS PageCreate Object of BL Class
CustomerBL ObjCustBL=new CustomerBL();
int64 Num=0;
Num=objCUstBL.GetNo();
textBox.text=Num.tostring();
Comments
Solution #6 is what I was looking for - how to bring a SQL Select statement from data access layer into UI layer of C# asp.net/web app! Thank you jay verma.
using microsoft enterprise library
using System;
using System.Text;
using System.Data;
using System.Collections.Generic;
using System.Data.Common;
using System.Data.SqlClient;
using System.Configuration;
using Microsoft.Practices.EnterpriseLibrary.Data;
using Microsoft.Practices.EnterpriseLibrary.Data.Sql
public static Database GetInstance()
{
if (database == null)
{
connectionString = ConfigurationManager.AppSettings["Database.Connection"].ToString();
database = new SqlDatabase(connectionString);
}
return database;
}
public DataSet RetrieveInfo(string paramter) { DataSet ds; DbCommand command = null; object[] @params = new object[1]; @params[0] = paramter; Database db = GetInstance(); command = db.GetStoredProcCommand("script or SP Name", @params); ds= db.ExecuteDataSet(command); command.Connection.Close(); return ds; }in your page , use below line of code
DataSet ds= issueDetails.RetrieveInfo(string paramter);
textbox.Text = ds.Tables[0].Rows[0]["name_of_db_column"].ToString();
namespace Access_to_Form { public partial class Previous : Form { public Previous() { InitializeComponent(); } System.Data.OleDb.OleDbConnection con; DataSet ds1; System.Data.OleDb.OleDbDataAdapter da; int Maxrows = 0; int inc = 0; private void Form1_Load(object sender, EventArgs e) { //create connection and fill dataset to dataadapter //then call NavigateRecords(); } private void NavigateRecords() { DataRow dRow = ds1.Tables["Tel"].Rows[inc]; .Text = dRow.ItemArray.GetValue(0).ToString(); .Text = dRow.ItemArray.GetValue(1).ToString(); .Text = dRow.ItemArray.GetValue(2).ToString(); .Text = dRow.ItemArray.GetValue(3).ToString(); .Text = dRow.ItemArray.GetValue(4).ToString(); .Text = dRow.ItemArray.GetValue(5).ToString(); } private void NextRecord_Click(object sender, EventArgs e) { if (inc != Maxrows - 1) { inc++; NavigateRecords(); } else { MessageBox.Show("No more Records"); } } private void button1_Click(object sender, EventArgs e) { if (inc > 0) { inc--; NavigateRecords(); } else { MessageBox.Show("First Record"); } } }
SqlCommand comando = new SqlCommand();
string myConnectionString = "Data Source=SERVER_NAME;Initial Catalog=DATABASE_NAME;Persist Security Info=True;User ID=USER_NAME; Password=USER_PASSWORD";
SqlConnection conn = new SqlConnection(myConnectionString);
comando.Connection = conn;
comando.CommandText = "SELECT COUNT(*) FROM TABELA";
conn.Open();
TextBox1.Text = comando.ExecuteScalar().ToString();
conn.Close();
cd: http://www.codeproject.com/Questions/155444/how-to-display-data-from-sql-database-to-textbox-u