I have written code for displaying content of a sql query on a webpage in aspx, I need to edit the column names of the returned result on the webpage. Below is the code for displaying content
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Configuration;
using System.Data.SqlClient;
using System.Data;
namespace XYZ
{
public partial class Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
string cs = ConfigurationManager.ConnectionStrings["ABC"].ConnectionString;
using (SqlConnection con = new SqlConnection(cs))
{
using (SqlDataAdapter sda = new SqlDataAdapter())
{
string queryString = "select * from asde";
SqlCommand cmd = new SqlCommand(queryString,con);
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
con.Open();
sda.SelectCommand = cmd;
SqlDataReader reader;
reader = cmd.ExecuteReader();
GridView1.DataSource = reader;
GridView1.DataBind();
}
}
}
}
}
any pointers in editing the column names is highly appreciated
You cannot set the datareader as the grid data source. Also data adapter should initialize with the sql command associated.
You can do something like below
SqlCommand cmd = new SqlCommand("select * from asde", con);
cmd.CommandType = CommandType.Text;
DataTable dt = new DataTable();
SqlDataAdapter da = new SqlDataAdapater(cmd);
da.Fill(dt);
GridView1.DataSource = dt;
GridView1.DataBind();
or
SqlDataReader dr = cmd.ExecuteReader();
DataTable dt = new DataTable();
dt.Load(dr);
GridView1.DataSource = dt;
GridView1.DataBind();
Related
My code
<form id="form1" runat="server">
<cc1:ToolkitScriptManager ID="ToolkitScriptManager1" runat="server">
</cc1:ToolkitScriptManager>
<cc1:Rating ID="Rating1" AutoPostBack="true" OnChanged="OnRatingChanged" runat="server"
StarCssClass="Star" WaitingStarCssClass="WaitingStar" EmptyStarCssClass="Star"
FilledStarCssClass="FilledStar">
</cc1:Rating>
<br />
<asp:Label ID="lblRatingStatus" runat="server" Text=""></asp:Label>
</form>
Rating.aspx
public partial class CS : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
DataTable dt = this.GetData("SELECT ISNULL(AVG(Rating), 0) AverageRating, COUNT(Rating) RatingCount FROM UserRatings");
Rating1.CurrentRating = Convert.ToInt32(dt.Rows[0]["AverageRating"]);
lblRatingStatus.Text = string.Format("{0} Users have rated. Average Rating {1}", dt.Rows[0]["RatingCount"], dt.Rows[0]["AverageRating"]);
}
}
private DataTable GetData(string query)
{
DataTable dt = new DataTable();
string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand(query))
{
using (SqlDataAdapter sda = new SqlDataAdapter())
{
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
sda.SelectCommand = cmd;
sda.Fill(dt);
}
}
return dt;
}
}
protected void OnRatingChanged(object sender, RatingEventArgs e)
{
string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand("INSERT INTO UserRatings VALUES(#Rating)"))
{
using (SqlDataAdapter sda = new SqlDataAdapter())
{
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("#Rating", e.Value);
cmd.Connection = con;
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
}
}
Response.Redirect(Request.Url.AbsoluteUri);
}
}
I found this code online.It is not working. I can not find any errors but it is not inserting records.In this output screen is shows 0 users have rated, Average Rating 0 even after you rate it.
I am new to Ajax and asp.net.If you can give any suggestions it would be helpful
THANK YOU.
I'm creating a new webservice in ASP.NET 5 using the new .NET Core library, so far I've only hit an issue with using DataSet and DataTable.
According to this site they are not included at this moment in time, which is fine, but I don't know what alternatives I have at this time, so I'm just looking for some guidance.
I have the following code:
public string Get(string p_sUserId, string p_sUserPassword, int p_iCustId)
{
Select qrySelect = new Select();
using (SqlConnection conn = new SqlConnection(Startup.ConnectionString))
{
using (SqlCommand cmd = new SqlCommand(qrySelect.getData(), conn))
{
cmd.Parameters.AddWithValue("#Id", sTestId);
using (SqlDataAdapter da = new SqlDataAdapter(cmd))
{
using (DataSet ds = new DataSet())
{
// foo
// bar
}
}
}
}
return "value";
}
How should I handle the data that is being return from the query? I need to build and return a string using the above data fetched from the query. Any help and guidance would be appreciated.
I believe SqlDataReader should work.
string sql = "SELECT * FROM Table";
using (SqlConnection con = new SqlConnection(Startup.ConnectionString)) {
con.Open();
using (SqlCommand command = new SqlCommand(sql, con)) {
using (IDataReader dr = command.ExecuteReader()) {
while (dr.Read()) {
//process data
}
}
}
}
DataTable and SqlDBAdapter are now supported using .NET Standard 2.0. Upgrade to VS2017 Preview, add System.Data.Common and System.Data.SqlClient nugets, and the code below should work. More detail at the blog post here -> https://blogs.msdn.microsoft.com/devfish/2017/05/15/exploring-datatable-and-sqldbadapter-in-asp-net-core-2-0/ . GitHub repo here -> https://github.com/jhealy/aspdotnetcore/tree/master/SqlClientPlay20 .
public static DataTable ExecuteDataTableSqlDA(SqlConnection conn, CommandType cmdType, string cmdText, SqlParameter[] cmdParms)
{
System.Data.DataTable dt = new DataTable();
System.Data.SqlClient.SqlDataAdapter da = new SqlDataAdapter(cmdText, conn);
da.Fill(dt);
return dt;
}
I have a very unique problem here...
If I'm going to select data from my database, my datatable will not get all of the database content using a SqlDataReader.
DataTable DTReader = new DataTable();
string Query = "SELECT CardCode FROM OCRD";
using (SqlConnection Connection = new SqlConnection(ConnString))
{
Stopwatch watch = new Stopwatch();
watch.Start();
Connection.Open();
using (SqlCommand Command= new SqlCommand(Query, Connection))
{
using (SqlDataReader reader = Command.ExecuteReader())
{
DTReader.Load(reader);
}
}
Connection.Close();
watch.Stop();
MessageBox.Show(watch.Elapsed.ToString());
gridControl1.DataSource = DTReader;
}
In OCRD we have some specific userdata where the cardcode is an unique identifier.
CardCode could be D40000, D410000,... and so on.
We definitely have D46000 codes but my datatable will not fetch them. From D40000 to D44999 we can get the data but we are unable to get data above.
The query is definitely correct...
Does anyone has any ideas regarding this issue ?
Thanks in advance.
I am stuck with this problem since yesterday. I have created a button, which when clicked display the results from a SQL Server table. I thought of using MessageBox to print these results or if there is any other way to print results?
private void button1_Click(object sender, EventArgs e)
{
try
{
SqlConnection con = new SqlConnection("Data Source=FAREEDH;Initial Catalog=DeakinsTrade;Integrated Security=True");
SqlCommand command = new SqlCommand("SELECT * FROM Products", con);
con.Open();
SqlDataReader reader = command.ExecuteReader();
command.ExecuteNonQuery();
con.Close();
}
catch (Exception es)
{
MessageBox.Show(es.Message);
}
}
I have tried different methods but it never worked.. I am really stuck. If you want more details, let me know. Thanks for the help in advance
Add a datagridview control to show multiple rows and try this code and rename it what you want and replace this YourDataGridVeiwName from the name you set for datagridview control and try below code
private void button1_Click(object sender, EventArgs e)
{
try
{
string connectionString = "Data Source=FAREEDH;Initial Catalog=DeakinsTrade;Integrated Security=True";
string query = "SELECT ProductName FROM Products;";
using (SqlConnection con = new SqlConnection(connectionString))
using (SqlCommand command = new SqlCommand(query, con))
{
con.Open();
using (SqlDataAdapter sda = new SqlDataAdapter(command))
{
DataTable dt = new DataTable();
sda.Fill(dt);
YourDataGridVeiwName.DataSource= dt;
}
con.Close();
}
}
catch (Exception es)
{
MessageBox.Show(es.Message);
}
}
You need to use the SqlDataReader and iterate over the rows returned, extract what you need from each row, and then display that to the enduser.
I modified your code a bit, to make it safer (using blocks!), and I modified the query to return only the product name (assuming you have that) since you cannot really display a whole row in a message box....
private void button1_Click(object sender, EventArgs e)
{
try
{
string connectionString = "Data Source=FAREEDH;Initial Catalog=DeakinsTrade;Integrated Security=True";
string query = "SELECT ProductName FROM Products;";
using (SqlConnection con = new SqlConnection(connectionString))
using (SqlCommand command = new SqlCommand(query, con))
{
con.Open();
using (SqlDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
string productName = reader.GetFieldValue<string>(0);
MessageBox("Product is: " + productName);
}
reader.Close();
}
con.Close();
}
}
catch (Exception es)
{
MessageBox.Show(es.Message);
}
}
I have made a web-service which'd give me the User Information.
[WebMethod]
public void Get_User_Info(string uid)
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["contest"].ConnectionString);
SqlCommand com = new SqlCommand("select * from mtblUser where UserId=#UserId", con);
com.CommandType = CommandType.Text;
com.Parameters.Add("#UserId", SqlDbType.NVarChar, 50).Value = uid;
SqlDataAdapter sda = new SqlDataAdapter(com);
DataTable dt = new DataTable();
sda.Fill(dt);
}
this web service is having 1 method Get_User_Info(). but when I try to use this method the namespane show 4 methods like below
Get_User_InfoRequest
Get_User_InfoRequestBody
Get_User_InfoResponse
Get_User_InfoResponseBody
how can I use my method please help.
Try
YourService.ServiceSoapClient _CurrentSrv = new YourService.ServiceSoapClient();
_CurrentSrv.Get_User_Info(YourId);