I am developing a windows form application in c#. My database is handled in a wcf application. In my wcf application I have a class called lecturer which has a method called view lecturers() as follows. My purpose is to view the lecturers table in a grid view.
public DataTable viewLec()
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["resourceAlloc"].ToString());
DataTable dt = new DataTable();
string vw = "select * from lecturers";
SqlCommand cmd = new SqlCommand(vw,con);
SqlDataAdapter adp = new SqlDataAdapter(cmd);
adp.Fill(dt);
return dt;
}
In my IService1.cs:
[OperationContract]
DataTable viewLecturer();
Service1.svc.cs:
public DataTable viewLecturer()
{
Lecturer lec = new Lecturer();
return lec.viewLec();
}
in my windows form application button click event,
private void button2_Click(object sender, EventArgs e)
{
Service1Client obj = new Service1Client();
dataGridView1.DataSource = obj.viewLecturer();
}
When I click the view button the above error occurs, I cannot understand why?
I don't know the exact error of your code, but first thing I want to mention is that using DataTable object as your Data Contract is not the best idea as it contains certain amount of extra data which usually is not consumed by the end applications. But anyway, in your particular case WCF will not be able to serialize your your object as it will not have table name which is mandatory for this class to perform serialization. Try to follow this way:
DataTable dt = new DataTable();
// Must set name for serialization to succeed.
dt.TableName = "lecturers";
I don't see the actual error you have (you should post it to make your answer more clear), but at least this will help you to avoid serialization error.
Related
I am a beginner at C# and .NET oop concepts. I want to load the datagridview. I don't know how to pass the data. What I tried so far I attached below.
I created a class std
public void get()
{
SqlConnection con = new SqlConnection("server =.; initial catalog=testdb; User ID=sa; Password=123");
string sql = "select * from std";
con.Open();
SqlCommand cm = new SqlCommand(sql, con);
SqlDataReader dr = cm.ExecuteReader();
while ( dr.Read())
{
string stname = dr["st_name"].ToString();
string nicnum = dr["nic"].ToString();
}
con.Close();
}
Form: I am getting data like this way
std ss = new std();
ss.get();
dataGridView1.Rows.Clear();
If I wrote like this way how to pass data into the datagridview columns? I am stuck in this area
It's easier like this:
public void FillGrid()
{
var dt = new DataTable();
var da = new SqlDataAdapter("select * from std", "server =.; initial catalog=testdb; User ID=sa; Password=123");
da.Fill(dt);
dataGridView1.DataSource = dt;
}
but if you're going to use such a low level method of database access you should consider adding a DataSet type of file to your project; visual studio will write all this code and more for you with a few mouse clicks, and it makes a good job of creating tables and adapters that are a lot easier to work with
you have made multiple mistakes. First you read data wirh dataraeader and in every iteration define two stname and nimnum variables like. So when loop ends variables are destroyed. You have to define data table and read data by dataraeader and and add them to it row by row. Or read by sqldataadapter and read it immediately and pass to datatable object.Finnaly you pass datatable as return object of function. Use this vala as datasource of datagridview property if I'm not wrong.
I'm doing an assignment in inserting and displaying data from SQL into a chart (using Web Form or Highchart) via WCF service. I was able to get the data from SQL to WCF service but I don't know how to display it into a chart. I know using Web Form I can directly bind the data from SQL to the chart but the purpose of the assignment is to display the data via WCF service. Here are my code:
TempService:
public DataSet GetTemp()
{
SqlConnection con = new SqlConnection();
con.ConnectionString = "server=DUCPC\\SQLEXPRESS;database=Temprature;user=sa;password=123456";
SqlDataAdapter da = new SqlDataAdapter("select * from RoomTemp",con);
DataSet ds = new DataSet();
da.Fill(ds);
return ds;
}
Code to bind the data to the chart in Web Form:
protected void Page_Load(object sender, EventArgs e)
{
TempService.TempServiceClient tsc = new TempService.TempServiceClient();
DataSet ds = tsc.GetTemp();
TempChart.DataSource = ds;
TempChart.DataBind();
}
Of course the above code not working. Can anyone help to fix the code above? Is there a simple way to insert the data into the SQL database? Any help is appreciated :)
This is my First report using SSRS.
I am trying to generate a Report using SSRS in asp.net.
My Need is:
I want to create a report with multiple tables (4 tables) that have relationship with one another. I have configured each individual table with accepting 1 parameter, for instance:
What I tried is:
I have created a dataset.xsd with 4 tables and given the relationship between those tables.
Then I created a report.rdlc and designed a report with four tables and drag and dropped the required field to the table and created a report parameter called ID.
The error i'm Getting is:
A data source instance has not been supplied for the data source 'DataSet2'
What I have written in cs page on button click is:
protected void BtnGo_Click(object sender, EventArgs e)
{
DataSet2TableAdapters.TB_TransReceiptTableAdapter ta = new DataSet2TableAdapters.TB_TransReceiptTableAdapter();
DataSet2.TB_TransReceiptDataTable dt = new DataSet2.TB_TransReceiptDataTable();
ta.Fill(dt,Convert.ToInt16( TxtID.Text));
//ta.Fill(dt,TxtID.Text);
ReportDataSource rds = new ReportDataSource();
rds.Name = "DataSet2";
rds.Value = dt;
ReportParameter rp = new ReportParameter("ID", TxtID.Text.ToString());
rptviewer.LocalReport.DataSources.Clear();
rptviewer.LocalReport.ReportPath = "Report1.rdlc";
rptviewer.LocalReport.SetParameters(new ReportParameter[] { rp });
rptviewer.LocalReport.DataSources.Add(rds);
rptviewer.LocalReport.Refresh();
rptviewer.Visible = true;
}
The help i seek is:
I dont know how to bind the report via code, since I have four tables that are related to one another with foreign key. Above is the code I used but it throws an error.
I would be very thankful if some one could help me to solve this issue.
Thanks in advance.
As per tgolisch instead of table i Bound dataset and passed to report it works fine.
And also instead of four separate table i created a view .It Makes my job simple
private DataTable getData()
{
DataSet dss = new DataSet();
string sql = "";
sql = "SELECT * from VW_TransReciptReport WHERE tREC_NUPKId='" + TxtID.Text + "'";
SqlDataAdapter da = new SqlDataAdapter(sql, con);
da.Fill(dss);
DataTable dt = dss.Tables[0];
return dt;
}
private void runRptViewer()
{
this.rptviewer.Reset();
ReportParameter rp = new ReportParameter("ID", TxtID.Text.ToString());
this.rptviewer.LocalReport.ReportPath = Server.MapPath("ReportReceipt.rdlc");
rptviewer.LocalReport.SetParameters(new ReportParameter[] { rp });
ReportDataSource rdsB = new ReportDataSource("DataSet1_VW_TransReciptReport", getData());
this.rptviewer.LocalReport.DataSources.Clear();
this.rptviewer.LocalReport.DataSources.Add(rdsB);
this.rptviewer.DataBind();
this.rptviewer.LocalReport.Refresh();
}
This is a windows forms application. I have a class Program.cs and a form DeployerConsole.cs with a ListBox on it. I am attempting to loop through the results from the SQL query. I am having trouble and getting a 'Object reference not set to an instance of an object.' error when I try to access the data and insert it into my listbox on the form.
EDIT: The SQL Query is completing successfully and the Console.WriteLine is outputting to the output window properly with the correct data.
static void LoadServers()
{
DeployerConsole DC = (DeployerConsole)Application.OpenForms["DeployerConsole"];
//DeployerConsole DC = new DeployerConsole();
SqlConnection myConnection = new SqlConnection("server=XXX; database=XXX; uid=XXX; pwd=XXX;Integrated Security=true;Connection Lifetime=5;Trusted_Connection=yes;");
myConnection.Open();
DataSet ds = new DataSet();
SqlCommand myCommand = new SqlCommand("SELECT ServerName FROM DeployServers", myConnection);
SqlDataAdapter adapter = new SqlDataAdapter(myCommand);
adapter.Fill(ds);
DataTable dt = ds.Tables[0];
foreach (DataRow dr in dt.Rows)
{
DC.listBox1.Items.Add(dr["ServerName"].ToString());
Console.WriteLine(dr["ServerName"].ToString());
}
}
EDIT: Added Screenshot
Anyone have any suggestions or provide guidance as to what I am doing wrong?
EDIT (ANSWER): Well, I moved the code from the class to the form. No problems accessing the listBox now. However, I still would like to know the solution to this.
It might be worth a try (just for testing purposes) to try:
if(DC.listBox1 != null)
{
DC.listBox1.Items.Add(dr["ServerName"].ToString());
}
That could give you a clue, if which you might need to make sure someplace listBox1 is instantiated.
DC.listBox1 = new ListBox();
EDIT
It might be that DC is not being correctly passed by reference to the static method.
It might be better to change the signature of the Method to accept the form.
static void LoadServers(Form form)
{
...
form.listBox1.Items.Add(...)
... etc.
}
and call it assuming from the form:
Helper.LoadServers(this);
Your problem is probably caused by this line of code:
DeployerConsole DC = (DeployerConsole)Application.OpenForms["DeployerConsole"];
I suspect the OpenForms property is returning null because you have not explicitly set the name of your form (e.g. form.Name = "DeployerConsole";).
At present i have a the following code populating a datagridview showing the user account information on our system. What i want to do do is have a checkbox on the datagridview for the option "accountenabled" and a update button at the bottom of the form so it will update all users that have had changes made against them. I am currently pulling the data back using an sqldatareader however from what i have read i need to use a sqldataadapter. I`ve created the column names on the datagridview and the reader is currently pulling everything back correctly.
Could someone please point me in the right direction of doing this with an sqldatadapter?
Thanks
public UserAdmin()
{
InitializeComponent();
//Load user list
// Locals
Functionality func = new Functionality();
SqlConnection supportDB = null;
SqlCommand CheckUser = null;
SqlDataReader rdr;
DataSet ds = new DataSet();
DataTable dt = new DataTable();
string User = System.Environment.UserName.ToString();
string spName = "gssp_ShowAllUsers";
try
{
using (supportDB = new SqlConnection(GSCoreFunc.ConnectionDetails.getConnectionString(ConnectionType.SupportDB)))
{
using (CheckUser = new SqlCommand(spName, supportDB))
{
// Set the command type
CheckUser.CommandType = CommandType.StoredProcedure;
// Populate the parameters.
CheckUser.Parameters.Add(func.CreateParameter("#spErrorID", SqlDbType.Int, ParameterDirection.Output, DBNull.Value));
// Open the connection and populate the reader with the SP output
supportDB.Open();
rdr = CheckUser.ExecuteReader();
if (CheckUser.Parameters["#spErrorID"].Value != null)
{
throw new InvalidOperationException();
}
// If the data reader has rows display output on label
if (rdr.HasRows)
{
//Output values
while (rdr.Read())
{
//Bind to data table
dgvUsers.Rows.Add(rdr["agentID"].ToString(), rdr["createdon"].ToString(), rdr["firstname"].ToString(), rdr["lastname"].ToString(), rdr["username"].ToString(), rdr["emailaddress"].ToString(), rdr["Departments"].ToString(), rdr["accountenabled"].ToString(), rdr["AgentAccountLevel"].ToString());
}
}
// Close reader and connection.
rdr.Close();
supportDB.Close();
}
}
}
catch (Exception ex)
{
//Show error message
string error = ex.ToString(); //Real error
string FriendlyError = "There has been error loading the user list"; // Error user will see
GSCoreFunc.ShowMessageBox.msgBoxErrorShow(FriendlyError);
//Log error to ExceptionDB
GSCoreFunc.ReportException.reportEx(GSCoreFunc.ApplicationInformation.ApplicationName, error, FriendlyError, GSCoreFunc.ApplicationInformation.ComputerName, GSCoreFunc.ApplicationInformation.OperatingSystem, GSCoreFunc.ApplicationInformation.screenSize, GSCoreFunc.ApplicationInformation.IPAdddress, GSCoreFunc.ApplicationInformation.domainName);// Pass error to GSCoreFunc to log to the ExceptionDB
}
}
private void btClose_Click(object sender, EventArgs e)
{
//Close window
Close();
}
}
}
There is nothing wrong with using the SqlDataReader. The SqlDataAdapter is a higher level api that allows you to iterate through an SqlDataReader and store a copy of the results in a DataTable or a DataSet. This copy can then be used as the data source for your DataGridView.
One thing I would change with your code would be to use data binding instead of generating each row manually. If you set the DataSource property of the grid to either your SqlDataReader or to a DataTable filled by an SqlDataAdapter and then call the grids DataBind() method the grid should be filled automatically with your data.
To control the columns you would make sure your query only returns the required columns, and you would define the column setup in your aspx-file.
Using data binding is generally an easier and more flexible approach, so you should consider using that instead.
Look at this code
Initialize a sql adapter and fill with data source . Use a connection string other than using sql data source because it would be easy for customizing. :)