Click here to Skip to main content
Rate this: bad
good
Please Sign up or sign in to vote.
See more: C# WinForm
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 8-Feb-11 22:41pm
ely z421
Edited 6-Sep-12 4:57am
v2
Comments
ely z at 9-Feb-11 4:36am
   
my program is 3layer
plz help
Micah David at 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 at 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.
aspnet_regiis at 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 at 8-Apr-14 9:08am
   
hbk,hnj,
 
ankurgupta999 at 14-Sep-12 4:44am
   
i have a form designed in vb.net , in this form in one text field i give ∂ sign but when i see in my database the sign changes and become ? is there any solution of such a problem
Rate this: bad
good
Please Sign up or sign in to vote.

Solution 1

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,
Smile | :)
  Permalink  
v2
Comments
Pradeep CBZ at 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 at 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
   
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
Ganesh Nikam at 7-Sep-12 1:41am
   
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
waseem-ricky at 14-Sep-12 2:10am
   
yes ganesh its perfect now..thanks yar
Member 10271562 at 6-Oct-13 8:07am
   
this my code i have to display database username in next form automatically .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();...bt its not working can any one help me
Member 10271562 at 6-Oct-13 8:07am
   
this my code i have to display database username in next form automatically .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();...bt its not working can any one help me
Member 10271562 at 6-Oct-13 8:07am
   
this my code i have to display database username in next form automatically .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();...bt its not working can any one help me
Member 10271562 at 6-Oct-13 8:07am
   
this my code i have to display database username in next form automatically .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();...bt its not working can any one help me
Ram Bhukya at 8-Apr-14 9:10am
   
Avunaaaaa
Ganesh Nikam at 25-Apr-14 3:16am
   
always welcome
waseem-ricky at 14-Sep-12 2:18am
   
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();
}
}
}
Ganesh Nikam at 14-Sep-12 2:18am
   
always welcome
Sam.S129 at 12-Oct-12 1:44am
   
Wonderful! Your solution is very helpful for me. Thanks very much!
Kishor Deshpande at 30-Jan-13 6:48am
   
For 3 layered, it's not correct solution, your data access and UI are in same layer :-(
Rate this: bad
good
Please Sign up or sign in to vote.

Solution 2

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();
                }
  Permalink  
Rate this: bad
good
Please Sign up or sign in to vote.

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();
  Permalink  
v2
Comments
Member 10271562 at 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();
Rate this: bad
good
Please Sign up or sign in to vote.

Solution 4

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");
}
 
}
}
  Permalink  
v2
Comments
Member 8597829 at 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 at 3-Feb-12 6:40am
   
da.Fill(ds);
What is ds?
Rate this: bad
good
Please Sign up or sign in to vote.

Solution 10

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.
  Permalink  
v3
Rate this: bad
good
Please Sign up or sign in to vote.

Solution 7

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];
  Permalink  
v2
Rate this: bad
good
Please Sign up or sign in to vote.

Solution 6

On DATA LAYER
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
CustomerDL ObjCustDL=new CustomerDL();
public int GetNo()
{
int Result;
result=objCustDL.GetNo();
return Result;
}
ON .CS Page
Create Object of BL Class
CustomerBL ObjCustBL=new CustomerBL();
int64 Num=0;
Num=objCUstBL.GetNo();
textBox.text=Num.tostring();
Hope It Will help You...Smile | :)
  Permalink  
v2
Comments
D.Steffen at 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.
Rate this: bad
good
Please Sign up or sign in to vote.

Solution 8

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();
  Permalink  
v2
Rate this: bad
good
Please Sign up or sign in to vote.

Solution 9

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");
            }
        } 
    }
  Permalink  
v3
Rate this: bad
good
Please Sign up or sign in to vote.

Solution 14

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
  Permalink  

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

  Print Answers RSS
0 Sergey Alexandrovich Kryukov 609
1 OriginalGriff 587
2 Maciej Los 325
3 Mathew Soji 195
4 BillWoodruff 190
0 OriginalGriff 7,356
1 Sergey Alexandrovich Kryukov 6,712
2 DamithSL 5,461
3 Manas Bhardwaj 4,916
4 Maciej Los 4,475


Advertise | Privacy | Mobile
Web04 | 2.8.1411023.1 | Last Updated 10 Nov 2014
Copyright © CodeProject, 1999-2014
All Rights Reserved. Terms of Service
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100