Displaying data from data reader c# in html web form - c#

I am using c# and i don't know how to write the data from c# in the HTML (to be available on the browser)
Here is my code :
public void searchbutton_Click(object sender , EventArgs e)
{
SqlConnection conn = new SqlConnection("Data Source=MAX-PC\\SQLEXPRESS;Initial Catalog=newSchool;Integrated Security=True");
SqlCommand cmd = new SqlCommand("search_name", conn);
cmd.CommandText = "exec search_name #name";
cmd.Parameters.AddWithValue("#name", search.Text);
conn.Open();
SqlDataReader reader = cmd.ExecuteReader();
conn.Close();
}
I want to know what to write in the HTML file to take the data from the reader
Thanks

You probably want to use a GridView control to display the data. http://msdn.microsoft.com/en-us/library/aa479342.aspx

Hope this helps
After the execute reader command do the following lines code for binding the data to the grid.
Also add a gridcontrol to the HTML to which the data has to be rendered.
DataSet ds = new DataSet();
DataTable dt = new DataTable("Table1");
ds.Tables.Add(dt);
ds.Load(read, LoadOption.PreserveChanges, ds.Tables[0]);
gridControl1.DataSource = ds.Tables[0];

Related

creating a list which works as inparameter for gridview

I'm working on a school development project and I'm quite new to development. I have been reading online but can't find the answer I'm looking for.
So far I have created a listbox in my Windows Forms application which I want to select all the values from one of my columns, and these should work as a inparameter to display data in my dataGridView based on the parameter.
I have created 70% of my project and this functionality is what is left. My database is in Azure and I can write to it and add new rows, but I can't read anything to my application when I run it.
code for listview, at first I just want to be able to select. Later on somehow write the choosen parameter to a variable that I can use as a condition in my dataGridView.
This is the code for my gridview so far I just want to display all data in it, but it's not showing anything.
namespace MyNamespace
{
public partial class CompanyForm : Form
{
public CompanyForm()
{
InitializeComponent();
}
//Connection String
string cs = ConfigurationManager.ConnectionStrings["ConnectionString"].
ConnectionString;
private void createCompany_Click_1(object sender, EventArgs e)
{
if (textBoxCompanyName.Text == "")
{
MessageBox.Show("Fill 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);
DataSet ds = new DataSet();
adapt.Fill(ds);
MessageBox.Show("GJ");
}
}
// The code that is not filling my datagrid
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;
}
}
}
}
My connection string is working it's already being able to insert data to the tables that I have.
The problem why you Grid isn't shown any data is that you try to bind a SqlDataReader to it. This isn't working, because the Grid doesn't support this as DataSource.
What you need as DataSource is DataTable, IList<T>, IBindingList<T>. In your case the DataTable would be the easiest solution. Try this out:
protected void DataEmployees()
{
using (SqlConnection con = new SqlConnection(cs))
{
con.Open();
SqlCommand cmd = new SqlCommand
(
"Select firstname,lastname FROM employees",con
);
SqlDataReader dr = cmd.ExecuteReader();
DataTable dt = new DataTable();
dt.Load(dr);
dataEmployees.DataSource = dt;
}
}
Notice that Methods are written Uppercase in C#. Further notice that you don't need to close the connection manually if you use a using-block. On the end of the using-block it's automatically closed/disposed.

Is it possible to fill a checkedlistbox with items from an sql database?

Sorry if this is a stupid question! I'm very new to coding and only have limited access to the internet whilst at work, I was just wondering if this is possible? and If so do you have a useful link for me to read over?
A quick overview of what I'm trying to do.
I have form1 and form2, form1 has a datagridview box that pulls data from the database, when I click on a cell it opens form2, which has a checklistbox which I want to now put code in so it pulls the data from a specific column and checks a box if the cell that was clicked applies to it.
Go easy on me if this question is stupid ^^, thanks in advance!
Some code I have produced so far! Which pulls the boxes from the database, but I also need to check the boxes too..
SqlConnection con = new SqlConnection("=");
con.Open();
string query = "select ID from dbo.report";
SqlCommand cmd = new SqlCommand(query, con);
SqlDataAdapter sda;
DataSet ds = new DataSet();
sda = new SqlDataAdapter(cmd);
sda.Fill(ds);
DataTable dt = ds.Tables[0];
foreach (DataRow datarow in dt.Rows)
{
checkedListBox1.Items.Add(datarow["ReportID"]);
Edited: put current coding in.
You can use below code to bind checkboxlist from database.
SqlConnection con = new SqlConnection("=");
con.Open();
string query = "select ID,NAME from dbo.report";
SqlCommand cmd = new SqlCommand(query, con);
SqlDataAdapter sda;
DataSet ds = new DataSet();
sda = new SqlDataAdapter(cmd);
sda.Fill(ds);
checkedListBox1.DataValueField = "ID"
checkedListBox1.DataTextField = "NAME"
checkedListBox1.DataSource = ds.Tables[0];
checkedListBox1.DataBind();

WebService ASP.NET C#

I have created a WebMethod in a WebService that uses stored procedures to find whatever you are searching for.
[WebMethod]
public DataSet getMyData(string search)
{
using (SqlConnection conn = new SqlConnection(#"Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Database1.mdf;Integrated Security=True;User Instance=True"))
{
conn.Open();
SqlCommand cmd = new SqlCommand("searchingads", conn);
SqlDataAdapter da;
DataSet ds = new DataSet();
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#search", search);
da = new SqlDataAdapter(cmd);
da.Fill(ds, "MyData");
conn.Close();
conn.Close();
return ds;
}
I don't know how to call this method from an ASP.NET application. I have a button that, when clicked, needs to call this method and populate a GridView.
I have the following code in my ASP.NET web application (on button click):
WebService1 service = new WebService1();
GridView2.DataSource = service.getMyData(TextBox1.Text);
GridView2.DataBind();
Label1.Text = service.HelloWorld();
The label switches to "hello world" when the button is clicked, but it doesn't give me any table when I do a search.
Thank you in advance for your help.
Please use this
GridView2.DataSource = service.getMyData(TextBox1.Text);
instead of
GridView2.DataSource = service.IskanjeOglasov(TextBox1.Text);
If you have tested your search logic and its returning the data then try by assigning the data table as data source not the data set.
GridView2.DataSource = ((DataSet)service.getMyData(TextBox1.Text)).Tables[0];
GridView2.DataBind();
Here I have removed the check part of dataset. This might work.

How to make Select Where statement in Windows Forms

I want to select all customer information where customerid = the selected customerid stored in the combo box and show the result in datagridview I tried this code but the gridview doesnot show result.
private void button1_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(constring);
int id = Convert.ToInt32(comboBox1.SelectedValue);
string cmdstring=string.Format("select *from customers where customer_id={0}",id);
SqlCommand cmd = new SqlCommand(cmdstring,con);
//cmd.Parameters.AddWithValue("#id",id);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
//da.Fill(ds, "customers");
//dataGridView1.DataSource = ds.Tables["customers"];
con.Open();
SqlDataReader red = cmd.ExecuteReader();
con.Close();
dataGridView1.DataSource = red;
button = new DataGridViewButtonColumn();
button.HeaderText = "edit";
button.Tag = ds.Tables["customers"].Columns["customer_id"];
dataGridView1.Columns.Add(button);
}
you could always make a DataBase Class and if you need to refactor this Class to pass in Connection String or read Connection string from .Config File you can use this as a template to get started plus it's a lot cleaner
Notice that I am returning a DataTable you can use this if you like just a suggestion
public class ClassDataManagement
{
public DataTable GetData(string sqlcmdString, string connString)
{
SqlConnection con = new SqlConnection(connString);
SqlCommand cmd = new SqlCommand(sqlcmdString, cn);
SqlDataAdapter da = new SqlDataAdapter(cmd);
con.Open();
DataTable dt = new DataTable();
da.Fill(dt);
return dt;
}
}
if you want to use DataSet instead of DataTable replace where i have DataTable with
or change the method to return a DataSet like this below
public DataSet GetData(string sqlcmdString, string connString)
{
SqlConnection con = new SqlConnection(connString);
SqlCommand cmd = new SqlCommand(sqlcmdString, cn);
SqlDataAdapter da = new SqlDataAdapter(cmd);
con.Open();
DataSet ds = new DataSet();
da.Fill(ds);
return ds;
}
after returning the ds you will need to bind it like this
dataGridView1.DataSource = ds;
dataGridView1.DataBind();
I'm fairly certain that you're not getting any data because you're closing the connection before binding, and because you're using an incompatible type as your data source:
con.Close();
dataGridView1.DataSource = red;
Set the data source prior to closing the connection, or at least be sure to populate the data (for data readers, the data are populated as you enumerate). Additionally, DataGridView.DataSource indicates that it must use one of four interfaces: IList, IListSource, IBindingList, and IBindingListSource. SqlDataReader does not support these. I recommend reading DataAdapters and DataReaders, as this outlines some of the features that are for populating this kind of control.

Question about displaying sql server data in a grid

I am pulling data from a sql server and putting it into a grid using c#. When the data displays on the grid, it is showing up as the guid rather than the actual name. How do I get the name to show and not the uniqe identifier. Any ideas? Thanks.
Here is some of the code:
public InventoryWindow()
{
InitializeComponent();
if (dgDataView != null)
{
SqlConnection con = new SqlConnection(connString);
SqlDataAdapter adpt = new SqlDataAdapter("select * from Item", con);
DataSet ds = new DataSet();
adpt.Fill(ds, "Item");
dgDataView.DataContext = ds;
//dgDataView.DataMember = "Item";
showdata();
}
}
private void showdata()
{
String connString = "server=server;database=database;user=user;password=password";
SqlConnection con = new SqlConnection(connString);
con.Open();
SqlCommand cmd = new SqlCommand("select * from Item", con);
SqlDataReader dr = cmd.ExecuteReader();
DataTable dt = new DataTable();
dt.Load(dr);
dgDataView.DataContext = dt;
con.Close();
}
You are using select * from Item and therefore returning all columns. You could just specify the columns you want in the Grid, in the order you want them. The grid by default has autocolumn generation on.
You can also specify the columns you want and what fields they map to using the columns DataMember values.
I figured this out, I just wrote my own query to display certain columns instead of automatically showing all of them.

Categories

Resources