Click here to Skip to main content
15,881,882 members
Please Sign up or sign in to vote.
3.14/5 (12 votes)
See more:
hi
i have a win form in C#.net
in this form there are row of number
i save numbers in sql db
i want to insert numbers to textbox from sql?
how do it?
Posted
Updated 15-Mar-19 0:18am
v2
Comments
ely z 9-Feb-11 4:36am    
my program is 3layer
plz help
Micah David 11-Apr-12 11:32am    
Please can someone help me with a code on visual studio c# on how to connect one select text field to sql database. It will be selecting a data from the database and display it on a new page. Please someone should help me, am also new in this forum.
Thanks,
Micah
sreeshan 11-Jul-12 6:57am    
hi,i want to know the coding for retrieve the data from database those data are display in allotted text box,please help me.
bbirajdar 13-Aug-12 6:10am    
You need to learn the basics of ADO.NET.. No use in yelling on online forums..We can help you solve specific difficulties but can not code you a complete functionality. Even if somebody provides you with the code, you will not be able to use it, since you don't have the basic knowledge on using somebody else's code..
Ram Bhukya 8-Apr-14 9:08am    
hbk,hnj,


Hi ely z,

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();




I hope yhis help,
:)
 
Share this answer
 
v2
Comments
Pradeep CBZ 12-Mar-12 23:19pm    
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
Member 10271562 6-Oct-13 8:02am    
Hi this is Gopinath. i have one problem in windows asp.net and c# CODING .actually i have to display username from database.the username already stored in database i have to display username in fron end of text box..while if i click even butten it will show in text box ..can any one suggest me ..right code
Joseph Ignacius Gono 26-Mar-15 1:26am    
hmm....
Member 11539242 24-Apr-15 12:34pm    
Thanks
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
C#
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();


ai vai a solução para funções que retornam apenas um valor.
Translated from Google Translator (not sure)- there goes solution for functions that return only one value.
 
Share this answer
 
v3
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":
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();
    }
 
Share this answer
 
C#
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();
 
Share this answer
 
v2
Comments
Member 10271562 6-Oct-13 8:05am    
i tried this code its not working i have one form .after login user need to register that form.ther i have to display the login person name for automatically in text box .
this my code
SqlConnection conn = new SqlConnection(strconnectionstring);
conn.Open();
SqlCommand cmd = new SqlCommand("select * from tb_adminregister where username='" + txtEmpName.Text.Trim() + "'", conn);
cmd.CommandText = "select * from tb_adminregister where username='" + txtEmpName.Text.Trim() + "'";
conn.Close();
MK_VEEE 27-Sep-22 3:52am    
Let'say if we have now textBox1.Text = DR1.GetValue(0).ToString(); textBox2.Text = DR1.GetValue(1).ToString(); textBox3.Text = DR1.GetValue(2).ToString(); and we want to loop all the textBox, then how to do that?
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
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");
}

}
}
 
Share this answer
 
v2
Comments
Member 8597829 29-Jan-12 3:01am    
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();
monmoy 3-Feb-12 6:40am    
da.Fill(ds);
What is ds?
C#
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];
 
Share this answer
 
v2
On DATA LAYER
C#
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 LAYER
Create Object of datalayer

Lets Name Of DL Be Customer
C#
CustomerDL ObjCustDL=new CustomerDL();
public int GetNo()
{
int Result;
result=objCustDL.GetNo();
return Result;
}

ON .CS Page
Create Object of BL Class
C#
CustomerBL ObjCustBL=new CustomerBL();
int64 Num=0;
Num=objCUstBL.GetNo();
textBox.text=Num.tostring();

Hope It Will help You...:)
 
Share this answer
 
v2
Comments
dmsWebDev 6-Feb-13 12:01pm    
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
C#
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

C#
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();
 
Share this answer
 
v2
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");
            }
        } 
    }
 
Share this answer
 
v3
obtain a value of number stored in datbase table
then CONVERT.To String(dr[0].ToString()) is used.to store value in txtbox...........







Gurwinder Singh
 
Share this answer
 
Comments
Member 12640137 17-Aug-16 0:49am    
I want to display picture in picture box. how is it possible? pls help me
Member 12764477 29-Sep-16 3:32am    
I have 2tables in sql database , i want to display 2 tables data in textbox's & taking one column as reference...here are the code

private void button5_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection("Integrated Security=SSPI;Initial Catalog=barcode");
SqlCommand cmd = new SqlCommand("select * from tblBarcodeTest1 LEFT JOIN Table_1 ON tblBarcodeTest1.code=Table_1.[Cutting Angle] where code like '" + textBox6.Text + "'", con);
con.Open();
SqlDataAdapter adp = new SqlDataAdapter();
SqlDataReader red = cmd.ExecuteReader();
while (red.Read())
{
textBox2.Text = Convert.ToString(red[0].ToString());
textBox2.Text = Convert.ToString(red[1].ToString());
textBox3.Text = red.GetString(2);
textBox4.Text = red.GetString(3);
textBox1.Text = red.GetString(5);
textBox5.Text = red.GetString(4);
textBox7.Text = Convert.ToString(red[6].ToString());
textBox9.Text = Convert.ToString(red[7].ToString());
textBox8.Text = Convert.ToString(red[8].ToString());
textBox10.Text = Convert.ToString(red[9].ToString());
textBox11.Text = Convert.ToString(red[10].ToString());
textBox12.Text = red.GetString(12);
textBox17.Text = Convert.ToString(red[11].ToString());
textBox13.Text =Convert.ToString(red[13].ToString());
textBox14.Text = red.GetString(0);
textBox15.Text = red.GetString(1);
textBox16.Text = Convert.ToString(red[2].ToString());
textBox18.Text = Convert.ToString(red[3].ToString());
textBox19.Text = red.GetString(4);
}
con.Close();
}

getting error at textbox14 and after remaining boz it is 2nd table data...
can anybody help me..
Member 13036486 4-Mar-17 3:31am    
I have created a desktop application form now i wanted whenever i select the select particular id in combobox rest of the form automatically filled with the data stored in it. Is there any way to do it
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();
 
Share this answer
 
Comments
CHill60 15-Mar-19 12:13pm    
Why open a second connection? Why be inconsistent with using ?
Why did you copy Solution 3?

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900