I have this table called FACILITIES. I am trying to have only one unique data in the FAC_TYPE field. In my data i have two meeting data. I only want to have one meeting data display inside only. I tried putting distinct in my code but it doesn't work. howwwww?
using System;
using System.Linq;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Configuration;
using System.Web.Security;
using System.Web.UI.HtmlControls;
using System.Data;
public partial class MainMenu : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
string constr = ConfigurationManager.ConnectionStrings["sacpConnectionString"].ToString(); // connection string
SqlConnection con = new SqlConnection(constr);
con.Open();
SqlCommand com = new SqlCommand("select distinct FAC_CODE, FAC_TYPE from FACILITIES", con);
SqlDataAdapter da = new SqlDataAdapter(com);
DataSet ds = new DataSet();
da.Fill(ds); // fill dataset
ddlMedicalCentre.DataTextField = ds.Tables[0].Columns["FAC_TYPE"].ToString(); // text field name of table dispalyed in dropdown
ddlMedicalCentre.DataValueField = ds.Tables[0].Columns["FAC_CODE"].ToString(); // to retrive specific textfield name
ddlMedicalCentre.DataSource = ds.Tables[0]; //assigning datasource to the dropdownlist
ddlMedicalCentre.DataBind(); //binding dropdownlist
}
}
}
the reason why it happening is because you might have different code but same name if you want distinct by name use
"select distinct FAC_TYPE, FAC_CODE, from FACILITIES"
Related
I am working on a C# Windows Forms application. I need to retrieve data into a datagridview from a SQL Server database.
How my program works:
Enter product code in the textbox
Click on the "Display button"
Then product details (name & price) related to the product code are loading to the first row of the datagridview.
I need to load the data to the very next row when this is done with another code.
But the problem is retrieving data is loading only in the first row by overwriting existing data. Not loading row by row.
How can I get data to the next row when it is searched by a product code without losing existing data in the datagridview? Any help would be much appreciated.
Image of my program
Here is my current code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.SqlClient;
namespace Retrieve_Data_In_Datagridview
{
public partial class Form1 : Form
{
SqlConnection conn = new SqlConnection("Data Source=.;Initial Catalog=InventoryManagement;Integrated Security=True");
public Form1()
{
InitializeComponent();
}
private void bind_data()
{
SqlCommand cmd = new SqlCommand("SELECT [product_code], [product_name], [price], [discounted_price] FROM [product_tab] WHERE [product_code] = #parm1", conn);
cmd.Parameters.AddWithValue("#parm1", textBox1.Text);
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = cmd;
DataTable dt = new DataTable();
dt.Clear();
da.Fill(dt);
dataGridView1.DataSource = dt;
//DataGridView1 navigating to next row
int nRow;
nRow = dataGridView1.CurrentCell.RowIndex;
if (nRow < dataGridView1.RowCount)
{
dataGridView1.CurrentCell = dataGridView1.Rows[++nRow].Cells[0];
}
}
private void button1_Click(object sender, EventArgs e)
{
bind_data();
}
}
}
The problem is basically that each time you do: dataGridView1.DataSource = dt; you change the source to a new Datatable that contains only the result of the last query.
Here is something like what you need:
[https://stackoverflow.com/questions/9608647/how-to-add-new-row-to-datagridview]
I have created a service based database in visual studio 2017. It works with a select statement but INSERT statement doesn't work. Here is my code.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Configuration;
using System.Data.SqlClient;
namespace RestaurantApp
{
public partial class Form1 : Form
{
SqlConnection conn = new SqlConnection(#"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\SerinCafe.mdf;Integrated Security=True");
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
conn.Open();
SqlCommand cmd = new SqlCommand("INSERT INTO Product (Id, ProductDescription, UnitPrice, SystemDate) Values (1,'Çay', 1, '01.01.2017')", conn);
cmd.ExecuteNonQuery();
SqlCommand cmd1 = new SqlCommand("SELECT * FROM Product", conn);
SqlDataAdapter da = new SqlDataAdapter(cmd1);
DataTable dt = new DataTable();
da.Fill(dt);
conn.Close();
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void button2_Click(object sender, EventArgs e)
{
Application.Exit();
}
I saw the same problem on different topics but there wasn't a clear solution that applies for me.
EDIT: On the SQL Server Object Explorer there is another database under the folder debug/bin. Now I checked it and I saw that data is inserted as I wanted. But it doesn't stay same. I changed the sql query as id = 3 and checked again. Previous data has gone. Newly inserted data is only there.
I have tested the code it works fine.Make sure you provided the connection string correctly.
I want to view this table in the list box in C#
enter image description here
I'm using this query to show the table
select
Chicken_Name, WithOrWithout_Name, Chicken_Price
from
Tbl_Add a
full outer join
tbl_Chicken b ON b.Chicken_ID = a.Chicken_ID
full outer join
Tbl_WithORWithot c ON a.WorWO_ID = c.WithOrWothout_ID ;
And this code to put it in the list box in C#
private void Chicken()
{
using (connection = new SqlConnection(connectionString))
using (SqlDataAdapter adapter = new SqlDataAdapter("select Chicken_Name,WithOrWithout_Name,Chicken_Price from Tbl_Add a full outer join tbl_Chicken b ON b.Chicken_ID = a.Chicken_ID full outer join Tbl_WithORWithot c ON a.WorWO_ID = c.WithOrWothout_ID ; ", connection))
{
DataTable tbl_Chicken = new DataTable();
adapter.Fill(tbl_Chicken);
lst_SHowdata.DisplayMember = "Chicken_Name";
lst_SHowdata.ValueMember = "Chicken_ID";
lstSHowdata2.DisplayMember = "Chicken_Price";
lst_SHowdata.DataSource = tbl_Chicken;
lstSHowdata2.DataSource = tbl_Chicken;
This is the full code
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Configuration;
using System.Data.SqlClient;
namespace HABIBIS_GRILL
{
public partial class HabibisGrll : Form
{
SqlConnection connection;
string connectionString;
public HabibisGrll()
{
InitializeComponent();
connectionString = ConfigurationManager.ConnectionStrings["HABIBIS_GRILL.Properties.Settings.HabibisGrilllDataBAseConnectionString"].ConnectionString;
}
private void Form1_Load(object sender, EventArgs e)
{
Chicken();
}
private void Chicken()
{
using (connection = new SqlConnection(connectionString))
using (SqlDataAdapter adapter = new SqlDataAdapter("select Chicken_Name,WithOrWithout_Name,Chicken_Price from Tbl_Add a full outer join tbl_Chicken b ON b.Chicken_ID = a.Chicken_ID full outer join Tbl_WithORWithot c ON a.WorWO_ID = c.WithOrWothout_ID ; ", connection))
{
DataTable tbl_Chicken = new DataTable();
adapter.Fill(tbl_Chicken);
lst_SHowdata.DisplayMember = "Chicken_Name";
lst_SHowdata.ValueMember = "Chicken_ID";
lstSHowdata2.DisplayMember = "Chicken_Price";
lst_SHowdata.DataSource = tbl_Chicken;
lstSHowdata2.DataSource = tbl_Chicken;
}
}
}
}
The problem is I need to use one list box for each column, how to make them in one list box or do I use another tool ?
And how to put 2 or more tables in one datatable (adapter) ?
Thank you ^^"
first question:
you can use gridview for your query if you want to show more than 1 column from your query.
Second question:
and you can use DataSet to get more than 1 table in case you need.
check this:
string queryCustomer =
"SELECT CustomerID, CompanyName FROM dbo.Customers";
SqlDataAdapter adapter = new SqlDataAdapter(queryCustomer , connection);
DataSet dataSet = new DataSet();
adapter.Fill(dataSet , "Customers");
string queryOrders =
"SELECT OrderId, Date FROM dbo.Orders";
SqlDataAdapter adapterOrder = new SqlDataAdapter(queryOrders , connection);
adapterOrder.Fill(dataSet , "Orders");
//assume you have a GridView named myGridview.
//than set its DataSource to one of your DataSet tables.
myGridview.DataSource = dataSet.Tables[0] //customers will be the source
Hey I'm trying to add database info into my webpage. This is the code I am trying.
using System;
using System.Windows;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Text;
using System.Configuration;
using System.Data.SqlClient;
namespace DatabaseAddDemo
{
public partial class Content : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (Request.QueryString["key"] != null)
{
try
{
SqlConnection sqlConn = new SqlConnection(#"Data Source=officedev1;Initial Catalog=TestDatabase;User ID=sa;Password=Password11;pooling='true';Connect Timeout=3000; Max Pool Size=200;MultipleActiveResultSets='true'");
SqlCommand cmdPreWork = new SqlCommand(#"select * from CKEditor_Table where #ID = #key", sqlConn);
string key = Request.QueryString["keys"].ToString();
contentLiteral.Text = key;
cmdPreWork.Parameters.Add("#Information", SqlDbType.Char).Value = key;
Console.WriteLine(contentLiteral);
SqlDataAdapter daPreWork = new SqlDataAdapter(cmdPreWork);
DataTable dtPreWork = new DataTable();
daPreWork.Fill(dtPreWork);
Grid.DataSource = dtPreWork;
Grid.DataBind();
}
catch (Exception ex)
{
lblError.Text = "Could not open connection";
}
}
}
}
}
Whenever I try to display the information, I get the lblError text, telling me I could not open the connection. I'm not sure what to do. Please help.
You should be able to DEBUG this as stated in the comments. But in your code your select query expects a [Key] parameter and you are passing a [Information] parameter.
Change it as below:
SqlCommand cmdPreWork = new SqlCommand(#"select * from CKEditor_Table
where #ID = #key", sqlConn);
cmdPreWork.Parameters.Add("#key", SqlDbType.Char).Value = key;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
public partial class RepeaterEx2 : System.Web.UI.Page {
SqlConnection cn = null;
SqlDataAdapter da = null;
DataSet ds = null;
String strSqlQuery = String.Empty;
protected void Page_Load(object sender, EventArgs e)
{
cn = new SqlConnection();
cn.ConnectionString = "Server=(local);Data base=TestDb;Uid=sa;Password=123";
if (!Page.IsPostBack)
{
}
}
void BindEmpData
{
SqlDataAdapter da=new SqlDataAdapter( "select e.ENO,e.ENAME,e.JOB,e.SAL,d.DNAME form EMPLOYEE e,DEPARTMENT d where e.DNO=d.DNO",cn);
da.Fill(ds,"EMPLOYEE");//here showing set or get accessorexpected error at "da"
Repeater1.DataSource=ds.Table["EMPLOYEE"];
Repeater1.DataBind();
}
}
I'm getting this error:
A get or set accessor expected
How do I resolve this error?
You need parentheses after the function name here:
void BindEmpData()
{
...
}
Also, you'll want to make sure you initialize the DataSet correctly:
void BindEmpData()
{
SqlDataAdapter da = new SqlDataAdapter("select e.ENO,e.ENAME,e.JOB,e.SAL,d.DNAME form EMPLOYEE e,DEPARTMENT d where e.DNO=d.DNO",cn);
DataSet ds = new DataSet();
da.Fill(ds,"EMPLOYEE");
Repeater1.DataSource = ds.Table["EMPLOYEE"];
Repeater1.DataBind();
}
And at this point you can remove the ds and da class members, since they are no longer being used (they've been replaced by function variables).
Parentheses is required to differentiate a method from a property that requires the get/set syntax