What does 'GET OR SET ACCESSOR EXPECTED' mean? - c#

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

Related

Invalid Connection String on .Net Teradata connection

I am trying to connect Teradata using .Net with the below code.
But when I execute it, it throws an error stating Invalid connection string
on
TdDataAdapter adapter = new TdDataAdapter(cn.ConnectionString,cmd.CommandText);
Here's the complete code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Teradata.Client.Provider;
using System.Data;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
TdConnectionStringBuilder connectionStringBuilder = new TdConnectionStringBuilder();
connectionStringBuilder.DataSource = "URK";
connectionStringBuilder.Database = "DB";
connectionStringBuilder.UserId = "USERNAME";
connectionStringBuilder.Password = "PASSWORD";
connectionStringBuilder.AuthenticationMechanism = "LDAP";
TdConnection cn = new TdConnection();
cn.ConnectionString = connectionStringBuilder.ConnectionString;
cn.Open();
TdCommand cmd = new TdCommand("EXEC MACRONAME", cn);
TdDataReader reader = cmd.ExecuteReader();
TdDataAdapter adapter = new TdDataAdapter(cn.ConnectionString,cmd.CommandText);
DataSet ds = new DataSet();
adapter.Fill(ds);
myLabel.Text= ds.Tables[0].Rows[0]["event_id"].ToString();
cmd.Dispose();
cn.Close();
}
}
I tried using connectionStringBuilder.ConnectionString instead of the one used above but I still got the same error.
Just swap parameters
TdDataAdapter adapter = new TdDataAdapter(cmd.CommandText, cn.ConnectionString);
according to signature of TdDataAdapter constructor
public TdDataAdapter(
string commandText,
string connectionString
)
See docs

method is not being called by application

My method is not being called by my application. I've used breakpoints and it's never initiated in the code. I'm building a C# Windows Forms application using an Azure Database, but the DataGridView is never being filled neither is the code being called at all... I have noooo clue whatsoever why..
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;
using System.Configuration;
namespace MyWinFormsProj
{
public partial class CompanyForm : Form
{
public CompanyForm()
{
InitializeComponent();
}
//Connection String
string cs = ConfigurationManager.ConnectionStrings
["MyConnetion"].ConnectionString;
// Load all employees
private void dataEmployees_Load()
{
using (SqlConnection con = new SqlConnection(cs))
{
con.Open();
SqlCommand cmd = new SqlCommand
(
"Select fname,ename FROM dbo.Users", con
);
SqlDataReader dr = cmd.ExecuteReader();
DataTable dt = new DataTable();
dt.Load(dr);
dataEmployees.DataSource = dt;
}
}
// Crate company
private void createCompany_Click_1(object sender, EventArgs e)
{
if (textBoxCompanyName.Text == "")
{
MessageBox.Show("Fill out information");
return;
}
using (SqlConnection con = new SqlConnection(cs))
{
//Create SqlConnection
con.Open();
SqlCommand cmd = new SqlCommand(
"insert into dbo.Company (companyName)
values(#companyName)", con);
cmd.Parameters.AddWithValue(
"#companyName", textBoxCompanyName.Text);
SqlDataAdapter adapt = new SqlDataAdapter(cmd);
MessageBox.Show("Grattis! Du har skapat ett företag");
}
}
}
}
The second method is working and is doing what it is supposed to do, but the first one is never called..
you need to set an event handler on the gridView onLoad and pass this method to the handler
public void GridView_OnLoad(object sender, EventArgs e)
{
dataEmployees_Load();
}
You need to fix your method signature to look like this:
private void dataEmployees_Load(object sender, EventArgs e)
Then, in your GirdView, you need to set this function as handler for event "onload":
OnLoad="dataEmployees_Load"
Thank you guys for your answers it helped my solve the problem. Like you were saying the problem was in the method not being called. So I called it directly on initiliazeComponent like this.
public partial class CompanyForm : Form
{
public CompanyForm()
{
InitializeComponent();
Load += new EventHandler(dataEmployees_Load); //Added this code
}
// Load all employees
private void dataEmployees_Load(object sender, EventArgs e)
{
using (SqlConnection con = new SqlConnection(cs))
{
con.Open();
SqlCommand cmd = new SqlCommand
(
"Select fname,ename FROM dbo.Users", con
);
SqlDataReader dr = cmd.ExecuteReader();
DataTable dt = new DataTable();
dt.Load(dr);
dataEmployees.DataSource = dt;
}
}

C# ASP.NET - SImplify number of SQL queries written in code

Here's a little background on what I'm doing...
I'm writing a C# web app. On the main page, I have a data input form with about 25 individual Dropdownlists. I created a table called options, and it's pretty simple (ID, Category, Option). Each option I create is categorized so my query will only include options that match the category I'm looking up. Each Category matches one of the 25 Dropdownlists I need to populate.
So I'm able to get a few of these populated on the form and they work great. I'm concerned that the re-writing of this code (with slight variation of the DDlist name and category name) will cause the code to be much longer. Is there a way I can create a class of it's own and pass parameters to the class so it only returns me data from the correct category and populates the correct Dropdownlist? Here's some sample code I have so far for 2 DD fields. The DDStationList and DDReqeustType are the names of 2 of the 25 Dropdownlists I have created:
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;
using System.Configuration;
using System.Drawing;
namespace TEST
{
public partial class _Default : Page
{
//Main connection string
string SqlConn = ConfigurationManager.AppSettings["SqlConn"];
string qryRequestType = ConfigurationManager.AppSettings["qryRequestTypes"];
string qryStationNumbers = ConfigurationManager.AppSettings["qryStationNumbers"];
protected void Page_Load(object sender, EventArgs e)
{}
protected void BtnAddNew_Click(object sender, EventArgs e)
{
//GET Request Types
DataTable RequestTypes = new DataTable();
SqlConnection Conn = new SqlConnection(SqlConn);
{
SqlDataAdapter adapter = new SqlDataAdapter(qryRequestType, Conn);
adapter.Fill(RequestTypes);
DDRequestType.DataSource = RequestTypes;
DDRequestType.DataTextField = "Option";
DDRequestType.DataValueField = "Option";
DDRequestType.DataBind();
}
// Get Stations
DataTable Stations = new DataTable();
SqlConnection Conn = new SqlConnection(SqlConn);
{
SqlDataAdapter adapter = new SqlDataAdapter(qryStationNumbers, Conn);
adapter.Fill(Stations);
DDStationList.DataSource = Stations;
DDStationList.DataTextField = "Option";
DDStationList.DataValueField = "Option";
DDStationList.DataBind();
}
}
protected void BtnSubmit_Click(object sender, EventArgs e)
{
//More stuff to do here for submit code
}
}
}
Example queries from my config file that correspond to above code:
SELECT [Option] FROM Table WHERE Category = 'RequestType';
SELECT [Option] FROM Table WHERE Category = 'Station';
So, is it possible I can create a class that I can pass the Option's Category into that runs the query Like this:
SELECT [Option] FROM Table WHERE Category = #Category;
...and then populate the correct Dropdownlist (need to do this 25 times)?
If I'm not clear on my question, I'll be happy to explain further.
Why not create a stored procedure instead?
using (SqlConnection con = new SqlConnection(dc.Con)) {
using (SqlCommand cmd = new SqlCommand("sp_GetCategory", con)) {
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("#Category", SqlDbType.VarChar).Value = txtCategory.Text;
con.Open();
var results = cmd.ExecuteReader();
}
}
OR include the parameter
string sql = "SELECT [Option] FROM Table WHERE Category = #Category";
using (SqlConnection con = new SqlConnection(dc.Con)) {
using (SqlCommand cmd= new SqlCommand(sql, con)) {
cmd.Parameters.Add("#Category", SqlDbType.VarChar).Value = txtCategory.Text;
con.Open();
var results = cmd.ExecuteReader();
}
}
EDIT
class Category
{
/* properties */
/* method */
public List<Category> GetCategory(string selectedCategory)
{ /* Method statements here */ }
}

Trying to select distinct on my dropdownlist

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"

Is it possible to use the dataset generated dynamically in the report viewer?

I am new to Windows Desktop Application Development.
I want to print the bill in my application and I have used a report viewer control and placed two labels to display the Bill No and Party Name.
I am creating the dataset in code behind file in C#.
I am assigning the value of dataset cell to the text property of the label. My code is:
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;
using System.Data.OleDb;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
OleDbConnection cn;
OleDbCommand cmd;
OleDbDataAdapter da;
DataSet ds;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
cn = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=D:\\Bill\\dbBill.accdb");
string query = "select A.BillNo,A.BillType,A.TaxType,A.PartyName,B.Desc,B.Desc,B.HSNCode,B.Qty,B.Rate,(B.Qty*B.Rate) as Amount " +
"from BillMaster A inner join BillDetail B on B.BillNo=A.BillNo";
cn.Open();
cmd = new OleDbCommand(query, cn);
da = new OleDbDataAdapter(cmd);
ds = new DataSet();
da.Fill(ds);
cn.Close();
// TODO: This line of code loads data into the 'dbBillDataSet.BillDetail' table. You can move, or remove it, as needed.
this.BillDetailTableAdapter.Fill(this.dbBillDataSet.BillDetail);
this.reportViewer1.RefreshReport();
}
private void reportViewer1_Load(object sender, EventArgs e)
{
lblBillNo.Text = ds.Tables[0].Rows[0]["BillNo"].ToString();
lblParty.Text = ds.Tables[0].Rows[0]["PartyName"].ToString();
}
}
}
How to assign the dataset values to the controls placed inside the report viewer control.
Please help me. Thanks in advance.
You wont be able to access DataSet instance ds inside of reportviewr_load. I would suggest you to make a function() which will return a DataSet and use that function() inside of the reportviewr_load.
private DataSet YourData()
{
cn = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=D:\\Bill \\dbBill.accdb");
string query = "select
A.BillNo,A.BillType,A.TaxType,A.PartyName,B.Desc,B.Desc,B.HSNCode,B.Qty,B.Rate,
(B.Qty*B.Rate) as Amount " +
"from BillMaster A inner join BillDetail B on B.BillNo=A.BillNo";
cn.Open();
cmd = new OleDbCommand(query, cn);
da = new OleDbDataAdapter(cmd);
ds = new DataSet();
da.Fill(ds);
cn.Close();
return ds;
}

Categories