Need help figuring out a gridview what am I doing wrong? - asp.net

How can I get the data to show on the gridview, anybody see what I'm doing wrong?
<asp:GridView ID="xTimeGridView"
runat="server" AllowSorting="True"
AutoGenerateColumns="False">
<Columns>
<asp:BoundField DataField="CLOCK_IN_TIME"
HeaderText="CLOCK_IN_TIME"
SortExpression="CLOCK_IN_TIME" />
<asp:BoundField DataField="CLOCK_OUT_TIME"
HeaderText="CLOCK_OUT_TIME"
SortExpression="CLOCK_OUT_TIME" />
</Columns>
string cmdquery = "SELECT * FROM EMPLOYEES WHERE BADGE ='" + Badge + "'";
OracleCommand cmd = new OracleCommand(cmdquery);
cmd.Connection = conn;
cmd.CommandType = CommandType.Text;
conn.Open();
using (OracleDataReader reader = cmd.ExecuteReader())
{
while (reader.Read())
{
this.xUserNameLabel.Text += reader["EMPLOYEE_NAME"];
this.xDepartmentLabel.Text += reader["REPORT_DEPARTMENT"];
}
}
conn.Close();
string hrquery = "SELECT CLOCK_IN_TIME, CLOCK_OUT_TIME FROM CLOCK_HISTORY WHERE BADGE='" + Badge + "'";
OracleCommand time = new OracleCommand(hrquery);
time.Connection = conn;
time.CommandType = CommandType.Text;
conn.Open();
using (OracleDataReader readers = time.ExecuteReader())
{
while (readers.Read())
{
xTimeGridView.DataSource = readers;
xTimeGridView.DataBind();
}
}
conn.Close();

Oh, you've got a problem here.
Just so that you understand what's going on, in your code, you are trying to open up the data that you get, and loop through it all; I'm not sure but I think you are effectively re-binding your GridView to each line of data individually.
You don't want to iterate through all the data and "read" it, what you want to do is store your query's results in a bindable object (like a DataSet) so that you can glue your gridview to it.
Try something like this instead, be sure to add your try/catch's later:
OracleCommand time = new OracleCommand(hrquery);
time.Connection = conn;
time.CommandType = CommandType.Text;
conn.Open();
// new code starts below
DataSet data = new DataSet("my data");
OracleDataAdapter adapter = new OracleDataAdapter(time);
adapter.Fill(data);
conn.Close();
xTimeGridView.DataSource = data;
xTimeGridView.DataBind();

Related

Exporting only filtered data from gridview asp.net

So I've managed to get my admin area to export for the user to download into an xml file format. However I've put in place some filtering options so the user logged in can narrow down the results viewable. What I'm trying to acheive is then after the user applies these filters to be able to then export only the filtered data.
Code Below:
protected void ExportData_Click(object sender, EventArgs e)
{
string consString = ConfigurationManager.ConnectionStrings["TortoiseDBConnectionString"].ConnectionString;
StringBuilder sb = new StringBuilder();
using (SqlConnection con = new SqlConnection(consString))
{
con.Open();
string sql = ("SELECT [ID], [HouseNumber], [PropAddress], [Town], [County], [PostCode] FROM Zoopla;");
SqlCommand cmd = new SqlCommand(sql, con);
DataTable dt = new DataTable();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);
GridView1.DataBind();
cmd.Dispose();
con.Close();
string filename = "DownloadTest.xml";
System.IO.StringWriter tw = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter hw = new System.Web.UI.HtmlTextWriter(tw);
DataGrid dgGrid = new DataGrid();
dgGrid.DataSource = dt;
dgGrid.DataBind();
dgGrid.RenderControl(hw);
Response.ContentType = "application/vnd.ms-excel";
Response.AppendHeader("Content-Disposition", "attachment; filename=" + filename + "");
this.EnableViewState = false;
Response.Write(tw.ToString());
Response.End();
}
}
Filters are set as follows:
Filter By Weeks:
<asp:DropDownList ID="DropDownList1" runat="server" AutoPostBack="True" DataSourceID="TortoiseDBZoopla" DataTextField="Weeks" DataValueField="Weeks">
</asp:DropDownList>
Filter By Status:
<asp:DropDownList ID="DropDownList2" runat="server" AutoPostBack="True" DataSourceID="ZooplaProperties" DataTextField="PropStatus" DataValueField="PropStatus">
</asp:DropDownList>
Your gridview is filtered, but when you are exporting, you are running a new SQL query without the filters. You will need to either add a where clause to your query that filters the results, or persist your gridview datasource somehow (Viewstate, Session, Cache...) and use it as your export datasource.

How to check two different webforms having same value of textboxes

aspx
TextBox1.Text
World.aspx
TextBox1.Text
I want the pages Hello.aspx and World.aspx having same value of validation
please help me anybody have the idea about this
You need to save the value on the first page using cookies or database or something else.
Then retrieve the value in the second page and compare the values in the validation function or event.
using(SqlConnection cn = new SqlConnection(connStr))
{
using(SqlCommand cmd = new SqlCommand())
{
cmd.Connection = cn;
string sql = string.Format(#"select email from customers where customer_id = '{0}'", customer_id);
cmd.CommandType = CommandType.Text;
//try and catch block would go here
cmd.CommandText = sql;
cn.Open();
SqlDataReader rdr = cmd.ExecuteReader();
string email = rdr[0].ToString();
cn.Close();
}
}

int data type is not working as parameter

I have a GridView in which I have check box as Item Template, and I am updating the GridView when check box is changed. Here is my GridView code:
<Columns>
<telerik:GridTemplateColumn>
<ItemTemplate>
<asp:CheckBox ID="chkcelar" runat="server" Text="Clear" OnCheckedChanged="chkclearchng" AutoPostBack="true"/>
</ItemTemplate>
</telerik:GridTemplateColumn>
<telerik:GridBoundColumn DataField="BPV_NUM" DataType="System.Int64"
DefaultInsertValue="" HeaderText="BPV No" SortExpression="BPV_NUM"
UniqueName="BPV_NUM">
</telerik:GridBoundColumn>
</Columns>
and here is the c# code through which I am updating grid view
protected void chkclearchng(object sender, EventArgs e)
{
OleDbConnection con = new OleDbConnection("Data Source=sml; User ID=sml; Password=sml; provider=OraOLEDB.Oracle");
OleDbCommand cmd = new OleDbCommand();
CheckBox chkcelar = ((CheckBox)(sender));
GridDataItem row = ((GridDataItem)(chkcelar.NamingContainer));
long bpvnum = row.Cells[1].Text;
if (chkcelar.Checked ) {
cmd.CommandText = #"update sml.FND_01_11#wbg set CLR_FLG=1, CLR_DTE=sysdate where bpv_num=:bpv_num and bpv_dte=:bpv_dte";
}
else {
cmd.CommandText = #"update sml.FND_01_11#wbg set CLR_FLG=0, CLR_DTE=sysdate where bpv_num=:bpv_num and bpv_dte=:bpv_dte";
}
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
cmd.Parameters.Add(":bpv_num",OleDbType.BigInt).Value = bpvnum;
cmd.Parameters.Add(":bpv_dte",OleDbType.Date).Value = RadComboBox1.SelectedValue;
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
The problem is that when I change the check box this error appears:
Input string was not in a correct format.
Can anyone tell what may be the issue and how can I resolve it?
Change your code like this:
protected void chkclearchng(object sender, EventArgs e)
{
using (OleDbConnection con = new OleDbConnection("Data Source=sml; User ID=sml; Password=sml; provider=OraOLEDB.Oracle"))
{
con.Open();
using (OleDbCommand cmd = new OleDbCommand(null, con))
{
CheckBox chkcelar = ((CheckBox)(sender));
GridDataItem row = ((GridDataItem)(chkcelar.NamingContainer));
long bpvnum = Convert.ToInt64(row.Cells[1].Text);
if (chkcelar.Checked)
{
cmd.CommandText = #"update sml.FND_01_11#wbg set CLR_FLG=1, CLR_DTE=sysdate where bpv_num=#bpv_num and bpv_dte=#bpv_dte";
}
else
{
cmd.CommandText = #"update sml.FND_01_11#wbg set CLR_FLG=0, CLR_DTE=sysdate where bpv_num=#bpv_num and bpv_dte=#bpv_dte";
}
cmd.Parameters.Add(new OleDbParameter("#bpv_num", bpvnum));
cmd.Parameters.Add(new OleDbParameter("#bpv_dte", Convert.ToDateTime(RadComboBox1.SelectedValue)));
cmd.ExecuteNonQuery();
}
}
}
May be you should use
long bpvnum = long.Parse(row.Cells[1].Text);
if doesn'T work then on this line
cmd.Parameters.Add(":bpv_dte",OleDbType.Date).Value = RadComboBox1.SelectedValue
You need parameter type OleDbType.Date but you are assigning RadComboBox1.SelectedValue
so you need to convert your
RadComboBox1.SelectedValue to OleDbType.Date
or you should simply use DateTimePicker
instead of ComboBox
Using Quick window check what is the vaule returns on "row.Cells[1].Text".
The issue in your code is because of the wrong type conversion from "string" to "OleDbType.Date". So replace the following code
cmd.Parameters.Add(":bpv_dte",OleDbType.Date).Value = RadComboBox1.SelectedValue;
with the following code
cmd.Parameters.Add(New OleDb.OleDbParameter("#bpv_dte", OleDb.OleDbType.Date));
cmd.Parameters("#bpv_dte").Value = RadComboBox1.SelectedValue.ToString("d");
Also make sure to convert all types correctly to OleDbType if there are more lines used for insertion.

i want to use data reader & update statement at same time

here is code
String[] month=new String[12]{"January","February","March","April","May","June","July","August","September","Octomber","November","December"};
int day = DateTime.Now.Day;
int mon= DateTime.Now.Month;
mon = mon - 1; //because month array is with 0
Label1.Text = day.ToString();
if (day==21)
{
int j = 1;
SqlCommand cmd1 = new SqlCommand();
cmd1.Connection = MyConn;
cmd1.CommandText = "SELECT No_of_times,Dustbin_no from mounthly_data";
SqlDataReader MyReader = cmd1.ExecuteReader();
while (MyReader.Read())
{
String a = MyReader["No_of_times"].ToString();
String b = MyReader["Dustbin_no"].ToString();
SqlCommand cmd = new SqlCommand();
cmd.Connection = MyConn;
cmd.CommandText = "update Yearly_data set [" + month[mon] + "]='"+a+"' where Dustbin_no='"+b+"'"; //just see ["+month[mon+"] it's imp
i = cmd.ExecuteNonQuery();
}
MyReader.Close();
}
i got error as
There is already an open DataReader associated with this Command which must be closed first.
I think you should give us the rest of the code above this code block because I'm not sure how a ExecuteNonQuery is using up a datareader. But from what I can gather, what you probably want is to open two separate connections. Only one datareader can be open per connection at a time. Either you use two separate connections or you could maybe use a datatable/dataset for the result of both your queries.
EDIT: From the rest of your code, yes, using two connections would be the simplest answer. When a reader is open, the connection associated with it is dedicated to the command that is used, thus no other command can use that connection.
I would recommend using a DataTable as this OLEDB example shows:
public static void TrySomethingLikeThis()
{
try
{
using (OleDbConnection con = new OleDbConnection())
{
con.ConnectionString = Users.GetConnectionString();
con.Open();
OleDbCommand cmd = new OleDbCommand();
cmd.Connection = con;
cmd.CommandType = CommandType.Text;
cmd.CommandText = "SELECT * FROM Customers";
OleDbDataAdapter da = new OleDbDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
foreach (DataRow row in dt.AsEnumerable())
{
cmd.CommandText = "UPDATE Customers SET CustomerName='Ronnie' WHERE ID = 4";
cmd.ExecuteNonQuery();
}
}
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}

Getting results from a stored procedure to populate a GridView

I have a windows aspx form that I have a TextBox, Button and a GridView. The TextBox is stored as a variable #subschedule and passed to a stored procedure. What I'd like to do is to populate the results of that procedure into my GridView. Can anyone suggest a way to do this?
Thank you
Two popular options:
1.. Code Behind:
string subSchedule = txtSubSchedule.Text.Trim();
//you'll create a new class with a method to get a list of customers
//from your database as others answers have demonstrated
IEnumerable<Customer> custs = MyDataLayer.GetCustomers(subSchedule);
myGrid.DataSource = custs;
myGrid.DataBind();
2.. Use a SqlDataSource. This is a quick and dirty way to bind your ASP.NET server control to a stored procedure. It's got its easy implementation pros, and some other cons :
<asp:GridView id="myGrid"
runat="server"
AutoGenerateColumns="true"
DataSourceID="ds1" />
<asp:SqlDataSource
id="ds1"
runat="server"
ConnectionString="<%$ ConnectionStrings:MyNorthwind%>"
SelectCommandType="StoredProcedure"
SelectCommand="GetSchedule">
<SelectParameters>
<asp:ControlParameter name="SubSchedule"
ControlID="txtSubSchedule" Propertyname="Text"/>
</SelectParameters>
</asp:SqlDataSource>
Add a reference to System.Data.SqlClient
Then create a method for your calling your stored procedure... Maybe wrap it up in a class for database calls.
public static class DataBase
{
public static DataTable myProcedureName(String subSchedule)
{
var dt = new DataTable();
using (var cnx = new SqlConnection("myConnectionString"))
using (var cmd = new SqlCommand {
Connection = cnx,
CommandText = "myProcedureName",
CommandType = CommandType.StoredProcedure,
Parameters = {
new SqlParameter("#subSchedule", subSchedule)
}
})
{
try
{
cnx.Open();
dt.Load(cmd.ExecuteReader());
return dt;
}
catch (Exception ex)
{
throw new Exception("Error executing MyProcedureName.", ex);
}
}
}
}
Then call it...
gvMyGrid.DataSource = DataBase.myProcedureName(txtSubSchedule.Text);
gvMyGrid.DataBind();
You'll need to use the DataSource property:
DataTable dt = new DataTable();
// Open the connection
using (SqlConnection cnn = new SqlConnection(
"Data Source=.\sqlexpress;Initial Catalog=AcmeRentals;Integrated Security=True"))
{
cnn.Open();
// Define the command
using (SqlCommand cmd = new SqlCommand())
{
cmd.Connection = cnn;
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = storedProcedureName;
// Define the data adapter and fill the dataset
using (SqlDataAdapter da = new SqlDataAdapter(cmd))
{
da.Fill(dt);
}
}
}
// This is the key code; you can set the DataSource to "collection"
gridView.DataSource = dt.DefaultView;
gridView.DataBind();
Source: http://msmvps.com/blogs/deborahk/archive/2009/07/07/dal-retrieve-a-datatable-using-a-stored-procedure.aspx
command.CommandType = CommandType.StoredProcedure;
command.CommandText = "SPPUBLISHER";
adapter = new SqlDataAdapter(command);
adapter.Fill(ds);
connection.Close();
GridView1.DataSource = ds.Tables[0];
GridView1.DataBind();
Full Source..gridview from procedure

Resources