I am using windows forms and i want to create a method that will simply view all the data depending on the item inside the ComboBox in a datagridview.
private void InsertReceipt()
{
decimal Stub;
Stub = decimal.Parse(txtAmount.Text) / 2000;
SqlCommand cmd = new SqlCommand();
cmd.Connection = cn;
cmd.CommandType = CommandType.Text;
cmd.CommandText = "INSERT INTO Ticket(CustomerID, Date, Store, Amount, NoStub)" +
"VALUES (#CustomerID, #Date, #Store, #Amount, #NoStub) ";
cmd.Parameters.AddWithValue("#CustomerID", cboName.SelectedValue);
cmd.Parameters.AddWithValue("#Date", dtpDate.Value.Date.ToString());
cmd.Parameters.AddWithValue("#Store", txtStore.Text);
decimal amount = decimal.Parse(txtAmount.Text);
cmd.Parameters.AddWithValue("#Amount", amount);
cmd.Parameters.Add("#NoStub", SqlDbType.Decimal).Value = Stub;
cmd.ExecuteNonQuery();
}
This are the fields and I need to view all the data depending on the item inside the ComboBox.
Your question is very general and vague therefor it is difficult to be precise in the answer. If you just want to learn how to use the datagridview with windows forms you can find plenty information about it online.
I find dotnetpearls a good starting point
void FillData()
{
// 1
// Open connection
using (SqlCeConnection c = new SqlCeConnection(
Properties.Settings.Default.DataConnectionString))
{
c.Open();
// 2
// Create new DataAdapter
using (SqlCeDataAdapter a = new SqlCeDataAdapter(
"SELECT * FROM Animals", c))
{
// 3
// Use DataAdapter to fill DataTable
DataTable t = new DataTable();
a.Fill(t);
// 4
// Render data onto the screen
dataGridView1.DataSource = t;
}
}
}
If i may recomend that you work through a few tutorials and ask specific question where you are stuck (with error messages and so on)?
Use this method way for Bind Gridview with data from Database
protected void BindGridview()
{
using (SqlConnection con = new SqlConnection("Data Source=DatabaseName;Integrated Security=true;Initial Catalog=***"))//Connection string
{
con.Open();
SqlCommand cmd = new SqlCommand("Select CustomerID,Date,Store,Amount,NoStub FROM Ticket where ColumnName='"+ YourDrodownId.SlectedValue +"'", con);
SqlDataReader dr = cmd.ExecuteReader();
YourGridview.DataSource = dr;
YourGridview.DataBind();
con.Close();
}
}
Then set the autogeneratecolumns property to false in our Gridview control and call this method in inside of your page load or were you want !
And Here is a full sample's with a code !
http://www.dotnetpools.com/Article/ArticleDetiail/?articleId=2
http://forums.asp.net/t/1904884.aspx/1
Update:
In Desktop application :
http://www.freedotnetapps.com/sql/database-operations-and-datagridview-bind-in-net-desktop-application/
Related
I am trying to get the name of the employee from the database and fill it in the textbox for the respective employee id.
I tried this code but nothing is happening on the page. It just reloads and the textbox (name) is left blank only.
SqlConnection con = new SqlConnection(#"Data Source=DESKTOP-0FUUV7B\SQLEXPRESS;Initial Catalog=EmployeeDetails;Integrated Security=True");
con.Open();
SqlCommand cmd = new SqlCommand("select * from ProfessionalDetails where EmpId='"+EmployeeId.Text+"'", con);
SqlDataReader da = cmd.ExecuteReader();
while (da.Read())
{
Name.Text = da.GetValue(1).ToString();
}
con.Close();
Better solution is to execute the sql statement through Parameterized value.
The details of that process is given below:
using (SqlConnection con = new SqlConnection(live_connectionString))
{
using (SqlCommand cmd = new SqlCommand("Query", con))
{
con.Open();
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("#EmpId", employeeId);
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = cmd;
var ds = new DataSet();
da.Fill(ds);
string? name = ds.Tables[0].Rows[1]["Variable name"].ToString();
Name.Text =name;
};
}
}
As mentioned above in comments, you have lot of issues.
you should use using with the connection to dispose of them.
You should use parameterized queries to avoid SQL injection.
Put your code in try catch so that you can easily identify the root cause of the issue.
Define the connection string in config file three than defining in the c# code.
You don’t need to select all the columns. And please avoid select * in the query, instead just write your column name, as you want to select only one column here.
You can use ExecuteScalar, it’s used when you are expecting single value.
And first make sure that textbox has the expected value when you are calling this query.
As noted, use paramters, and BETTER use STRONG typed paramters.
And no need to use a dataset, this is a single table - so use a datatable.
thus:
string strSQL =
#"select * from ProfessionalDetails where EmpId= #ID";
using (SqlConnection con = new SqlConnection(Properties.Settings.Default.TEST4))
{
using (SqlCommand cmd = new SqlCommand(strSQL, con))
{
con.Open();
cmd.Parameters.Add("#ID", SqlDbType.Int).Value = EmployeeID.Text;
DataTable rstData = new DataTable();
rstData.Load(cmd.ExecuteReader());
if (rstData.Rows.Count > 0)
Name.Text = rstData.Rows[0]["Name"].ToString();
}
}
I have a form that include
:
2 Textedit
one for input Identifier_number and another to input prod_name
1 lookUpEdit
to select prod_cat from database
1 MemoEdit
to input prod_desc
1 pictureedit
to input the pic
2 simplebutton
one for save data to database and another to fetch the pic
Note Im using tool from devexpress
I want the user input data and the program save it in data base
this my code
private void btn_done_Click(object sender, EventArgs e)
{
String sql = "insert into prodects_tab (prod_id,Identifier_number,prod_name,prod_cat,prod_desc)"
+ "Values(#prod_id,#Identifier_number,#prod_name,#prod_cat,#prod_desc)";
using (SqlConnection cn = new SqlConnection(#"Server=.\SQLEXPRESS; Database=db_LPS_Supermarket; Integrated Security=true"))
{
using (SqlCommand cmd = new SqlCommand(sql, cn))
{
cmd.Parameters.Add("#prod_id", SqlDbType.Int).Value = 3;
cmd.Parameters.Add("#Identifier_number", SqlDbType.BigInt).Value = txt_sri_num.Text;
cmd.Parameters.Add("#prod_name", SqlDbType.VarChar).Value = txt_prod_name.Text;
cmd.Parameters.Add("#prod_cat", SqlDbType.Int).Value = cmb_Cat.Text;
cmd.Parameters.Add("#prod_desc", SqlDbType.VarChar).Value = txt_prod_desc.Text;
// cmd.Parameters.Add("#prod_pic", SqlDbType.Image).Value = pics_prod_img;
cn.Open();
cmd.ExecuteNonQuery();
cn.Close();
}
}
}
}
the error is in method ExecuteNonQuery()
and if anyone know how i can fatch the pic from picedit to database tell me
I am currently working on Invoice Software. I get struct in reading data from Access database. My question is about when i type 1st word of Product name the program do search in database and then show me related products names as traditional Billing software do. How can i do this?
You need to use AutoComplete Extender if you are creating a web application or AutoCompleteMode property of TextBox if it is a Windows desktop application.
Use a TextBox:
private void textBox1_TextChanged(object sender, EventArgs e)
{
string strProvider = #"Provider = Microsoft.ACE.OLEDB.12.0; Data Source = F:\product.accdb";
string strSql = "Select * from product where productname like '" + textBox1.Text + "*';" ;
OleDbConnection con = new OleDbConnection(strProvider);
OleDbCommand cmd = new OleDbCommand(strSql, con);
con.Open();
cmd.CommandType = CommandType.Text;
OleDbDataAdapter da = new OleDbDataAdapter(cmd);
DataTable products = new DataTable();
da.Fill(products);
dataGridView1.DataSource = products;
con.Close();
}
I just finished to make the add part of a quiz, the part where admin add questions for guest.
When I clicked next button I just see the last question I added. Here is the code:
SqlConnection con = new SqlConnection(#"Data Source=MARIA-PC;Initial Catalog=Account;Integrated Security=True");
con.Open();
SqlCommand cmd = new SqlCommand("SELECT * FROM [dbo].[QuestAdd] WHERE Class = '1'", con);
SqlDataReader reader = null;
reader = cmd.ExecuteReader();
while (reader.Read())
{
textBox2.Text = (reader["Question"].ToString());
textBox3.Text = (reader["R1"].ToString());
textBox4.Text = (reader["R2"].ToString());
textBox5.Text = (reader["R3"].ToString());
textBox6.Text = (reader["R4"].ToString());
if (textBox7.Text == (reader["R_correct"].ToString()))
point = point + 1;
}
con.Close();
My problem is That I don't know why I see just the last question althoug in the table I have more than one question.
The datareader is looping through all the results and overwriting the textbox values for each row in the query.
In the code above, every time you run this, only the final row retrieved will be displayed.
You might be better retrieving the data and storing in a data structure and recoding the next button to use this.
e.g.
//Set up datatable with all questions
DataTable dt=new DataTable();
dt.column.Add("Question",typeof(string));
dt.column.Add("R1",typeof(string));
dt.column.Add("R2",typeof(string));
dt.column.Add("R3",typeof(string));
dt.column.Add("R4",typeof(string));
dt.column.Add("R_correct",typeof(int));
SqlConnection con = new SqlConnection(#"Data Source=MARIA-PC;Initial Catalog=Account;Integrated Security=True");
con.Open();
SqlCommand cmd = new SqlCommand("SELECT * FROM [dbo].[QuestAdd] WHERE Class = '1'", con);
SqlDataReader reader = null;
reader = cmd.ExecuteReader();
while (reader.Read())
{
DataRow dr=dt.NewRow();
dr["Question"] = (reader["Question"].ToString());
dr["R1"] = (reader["R1"].ToString());
dr["R2"] = (reader["R2"].ToString());
dr["R3"] = (reader["R3"].ToString());
dr["R4"] = (reader["R4"].ToString());
dr["R_correct"] = (reader["R_correct"]);
dt.Rows.Add(dr);
}
con.Close();
I've used a datatable here but you could easily use a list of objects as well.
The code above just adds the data from the query into a datatable and you can then, in your next button, write code that changes the row number.
This is just a rough start but it should get you on the right track
I want to populate data from a SQL Server database from many columns to many textboxes .. I have a code to populate just one box .. can someone edit my code... I want to pull data and show it in Name, Address, Telephone No and Date ... plz help .. this code works for only one textbox..
Thanks in advance
SqlConnection Conn = new SqlConnection(#"Data Source=rex;Initial Catalog=PersonalDetails;Integrated Security=True");
SqlCommand Comm1 = new SqlCommand("Select * From PersonalUsers ", Conn);
Conn.Open();
SqlDataReader DR1 = Comm1.ExecuteReader();
if (DR1.Read())
{
Name.Text = DR1.GetValue(0).ToString();
}
while (DR1.Read())
{
if(DR1.GetName() == "YourSQLColumnName")
{
YourTextBox.Text = (string) DR1["YourSQLColumnName"];
}
// Your Other textboxes and columns which you want to match should follow as this template
}
SqlCommand cmd = new System.Data.SqlClient.SqlCommand(sql, _conn);
SqlDataReader rdr = cmd.ExecuteReader();
System.Data.DataTable tbl = new System.Data.DataTable("Results");
tbl.Load(rdr);
if (tbl.Rows.Count > 0)
Name.Text = tbl.Rows[0]["column_name"].ToString();
string cs=System.Configuration.ConfigurationManager.ConnectionString["DBCS"].ConnectionString;
using(OracleConnection con=new OracleConnection(cs))
{
sql="select empname from Emp where empno='"+empno+"'";
OracleCommand cmd = new System.Data.OracleClient.OracleCommand(sql,con);
con.Open();
OracleDataReader rdr = cmd.ExecuteReader();
if(rdr.Read())
{
EmpName.Text=Convert.ToString(rd["empname"]);
}
}
I assume that you would like to take care of both more rows and more columns.
Try to specify the columns. It works without, but the performance is better if you do so.
I assume you have a class called PersonalUser with the specifed properties.
It is also nice to have it in an sorted order, so I added that
public List<PersonalUser> FetchMyData()
{
SqlConnection Conn = new SqlConnection(#"Data Source=rex;Initial Catalog=PersonalDetails;Integrated Security=True");
SqlCommand Comm1 = new SqlCommand("Select Name, Address, TelephoneNo,Date From PersonalUsers order by Name", Conn);
Conn.Open();
SqlDataReader DR1 = Comm1.ExecuteReader();
var result = new List<PersonalUser>();
while (DR1.Read())
{
result.Add(new PersonalUser {
Name = DR1.GetString(0);
Address= DR1.GetString(1);
TelephoneNo = DR1.GetString(2);
Date = DR1.GetString(3)
}
);
}
return result;
}
I would also, if the need is getting much complex than this, conidering using Entity Framwork..