Getting results from a stored procedure to populate a GridView - asp.net

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

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.

setting a dropdownlist value from database on page load

Sounds like an easy job but havent been able to figure it out.I have an edit profile page where all the user data is pulled from database to respective textboxes,labels etc on Page_Load.The dropdownlist is binded to a table as below.My ddl is as below :
<asp:DropDownList ID="ddlGender" runat="server" Width="160px" AutoPostBack="True" OnDataBound="ddlGender_DataBound">
</asp:DropDownList>
and is binded as below :
protected void BindGenderDropDown()
{
string CS = ConfigurationManager.ConnectionStrings["SportsActiveConnectionString"].ConnectionString;
using (SqlConnection con = new SqlConnection(CS))
{
con.Open();
SqlCommand cmd = new SqlCommand("select * from tblGenders", con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
ddlGender.DataSource = ds;
ddlGender.DataTextField = "GenderName";
ddlGender.DataValueField = "GenderId";
ddlGender.DataBind();
}
ddlGender.Items.Insert(0, new ListItem("---Select---", "0"));
ddlGender.SelectedIndex = 0;
}
I am not able to set a value in the dropdownlist though.Here is what I have done :
private void ExtractData()
{
string CS = ConfigurationManager.ConnectionStrings["fgff"].ConnectionString;
using (SqlConnection con = new SqlConnection(CS))
{
con.Open();
SqlCommand cmd = new SqlCommand("Select * from tblRegPlayers1 where UserId='PL00011'", con);
SqlDataReader rdr = cmd.ExecuteReader();
while (rdr.Read())
{
string path = rdr["ProfilePicPath"].ToString();
hfImagePath.Value = Path.GetFileName(path);
txtFName.Text = rdr["FirstName"].ToString();
txtLName.Text = rdr["LastName"].ToString();
txtEmailAddress.Text = rdr["EmailAdd"].ToString();
txtContactNumber.Text = rdr["MobileNo"].ToString();
txtdob.Value = rdr["DOB"].ToString();
txtStreetAddress.Text = rdr["StreetAddress"].ToString();
txtZipCode.Text = rdr["ZipCode"].ToString();
ddlGender.Items.FindByText(rdr["Gender"].ToString()).Selected = true;
}
}
But it says 'Object is not set to an instance'. So i played around a bit and tried doing it in DataBound like this :
protected void ddlGender_DataBound(object sender, EventArgs e)
{
string CS = ConfigurationManager.ConnectionStrings["SportsActiveConnectionString"].ConnectionString;
using (SqlConnection con = new SqlConnection(CS))
{
con.Open();
SqlCommand cmd = new SqlCommand("Select * from tblRegPlayers1 where UserId='PL00011'", con);
SqlDataReader rdr = cmd.ExecuteReader();
while (rdr.Read())
{
ddlGender.Items.FindByText(rdr["Gender"].ToString()).Selected = true;
}
}
Now it doesnt throw any error and it doesnt select the value as well.
PS : 1.I have set Autopostback true for the ddl.
2.I am aware of sqlInjection and have made changes to make it look simpler.
My final PageLoad looks like this :
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
//btnReset.Visible = false;
ExtractData();
BindDisabilityDropDown();
BindGenderDropDown();
BindStateDropDown();
}
if (hfImagePath.Value == "" || hfImagePath.Value == "0")
{
imgCropped.ImageUrl = "~/ProfilePictures/DefaultProfilePicture.png";
hfImagePath.Value = "0";
}
else
{
imgCropped.ImageUrl = "~/ProfilePictures/" + hfImagePath.Value;
}
//lblRegistration.Text = Session["Button"].ToString();
}
For one, you are calling ExtractData before you have actually bound the DropDownList in the BindGenderDropDown method. This means that your dropdown will have no items when you try to look it up and set the selected item. First things first you need to move the databinding code above ExtractData.
Second, you are you trying to set the selected value in an unusual way. Instead of attempting to FindByText you should try setting SelectedValue instead.
I will assume that the contents of rdr["Gender"] in ExtractData is the GenderId you have bound to the dropdown, and not the display value in GenderName. I will also assume that GenderId is M and F and GenderName is Male and Female (although if your actual implementation varies slightly then that's ok).
Try changing:
ddlGender.Items.FindByText(rdr["Gender"].ToString()).Selected = true;
To:
ddlGender.SelectedValue = rdr["Gender"].ToString();
Also be sure to remove the code you have added for the DataBound handler, it is not necessary here.
DataSet ds = new DataSet();
da.Fill(ds);
ddlGender.DataSource = ds;
ddlGender.DataTextField = "GenderName";
ddlGender.DataValueField = "GenderId";
ddlGender.DataBind();
You are trying to set the value to a specific Column, yet you are binding it to a DataSet and not a DataTable. (A DataSet has no columns only DataTables).
Try the following assuming the DataSet has a table returned and the column names match your table structure:
string strDesiredSelection = "Male";
DataSet ds = new DataSet();
da.Fill(ds);
ddlGender.DataSource = ds.Tables[0];
ddlGender.DataTextField = "GenderName";
ddlGender.DataValueField = "GenderId";
ddlGender.DataBind();
foreach(ListItem li in ddlGender.Items){
if(li.Value.Equals(strDesiredSelection)){
ddlGender.SelectedIndex = ddlGender.Items.IndexOf(li);
}
}

Stored procedure doesnt return any value

I got simple problem but I got no idea about where is problem :/ So in my GridView I am using ObjectDataSource with custom paging like in this tutorial http://www.codedigest.com/Articles/ASPNET/180_Custom_GridView_Paging_with_ObjectDataSource_Control_with_ASPNet_20.aspx
Here is my aspx markup:
<asp:ObjectDataSource ID="ObjectDataSource2"
runat="server"
onselecting="ObjectDataSource2_Selecting"
EnablePaging="true"
SelectCountMethod="GetItemsCount"
SelectMethod="BindItems"
StartRowIndexParameterName="startRowIndex"
MaximumRowsParameterName="maximumRows"
TypeName="eSova.Utilities.RecordUtilities"
>
And method which calling:
public static DataTable BindItems(int category,int search,int startRowIndex,int maximumRows)
{
DataTable table = new DataTable();
using (SqlConnection connection = new SqlConnection())
{
ConnectionUtilities.OpenConnection(connection);
SqlTransaction transaction = connection.BeginTransaction();
try
{
SqlCommand command = new SqlCommand("GetItems",connection,transaction);
command.CommandType = CommandType.StoredProcedure;
command.Parameters.Add("#RowIndex", SqlDbType.Int, 4).Value = startRowIndex;
command.Parameters.Add("#MaxRows", SqlDbType.Int, 4).Value = maximumRows;
SqlDataAdapter adapter = new SqlDataAdapter(command);
adapter.Fill(table);
transaction.Commit();
}
catch
{
transaction.Rollback();
}
}
return table;
}
My stored procedure works just fine and return in all items from table.
But when I analyze the code, I got breakpoint on return and table variable is without records. I don't know where is problem.
UPDATE:
create proc [dbo].[GetItems](#RowIndex int,#MaxRows int)
as
declare #StartRows int
declare #EndRow int
set #StartRows=(#RowIndex+1)
set #EndRow=(#StartRows+#MaxRows)
select *
from ( select id, name, filepath, descript, itemlanguage,
filetypeid, ROW_NUMBER() over (ORDER by id)as row FROM Items)as NumberesItems
where row between #StartRows and #EndRow
Your connectionstring is empty.

Populate a couple of TextBoxes based on selection of a DropDownList

I have a DropDownList populated from a Database.
When I select an item in the DropDownList, I want to call a procedure and pass the value of the DropDownList to the calling procedure to query a database to populate a couple of Text Boxes.
How to do this?
Code for procedure:
protected void PopulateTextBoxes()
{
SqlDataReader MyReader;
SqlConnection Conn;
SqlParameter TourIdParam;
string strConnection = ConfigurationManager.ConnectionStrings["ChinatowndbConnString"].ConnectionString;
Conn = new SqlConnection(strConnection);
SqlCommand MyCommand = new SqlCommand();
MyCommand.CommandText = "SELECT TourId, TName, TDetails FROM Chinatowndb.dbo.Tour Where TourId = #TourIdp";
MyCommand.CommandType = CommandType.Text;
MyCommand.Connection = Conn;
TourIdParam = new SqlParameter();
TourIdParam.ParameterName = "#TourIdp";
TourIdParam.SqlDbType = SqlDbType.Int;
TourIdParam.Direction = ParameterDirection.Input;
TourIdParam.Value = ddlTour.SelectedItem.Value;
MyCommand.Parameters.Add(TourIdParam);
MyCommand.Connection.Open();
MyReader = MyCommand.ExecuteReader(CommandBehavior.CloseConnection);
while (MyReader.Read())
{
tbTourName.Text = (string)MyReader["TName"];
tbTourDetails.Text = (string)MyReader["TDetails"];
lblTourId.Text = Convert.ToString(MyReader["TourId"]);
}
}
Code to populate DropDownBox:
private void PopulateTour()
{
DataTable dtTour = new DataTable();
string strConnection = ConfigurationManager.ConnectionStrings["ChinatowndbConnString"].ConnectionString;
using (SqlConnection con = new SqlConnection(strConnection))
{
try
{
SqlDataAdapter adapter = new SqlDataAdapter("SELECT TourId, TName FROM Chinatowndb.dbo.Tour", con);
adapter.Fill(dtTour);
ddlTour.DataSource = dtTour;
ddlTour.DataValueField = "TourId";
ddlTour.DataTextField = "TName";
ddlTour.DataBind();
}
catch (Exception ex)
{
// Handle the error
}
}
// Add the initial item
ddlTour.Items.Insert(0, new ListItem("<Select Tour>", "0"));
}
You need to add the event handler for the selection change in your HTML
<asp:DropDownList id="ddlTour"
AutoPostBack="True"
OnSelectedIndexChanged="ddlTour_SelectedIndexChanged"
runat="server">
and process the event in your code behind
void ddlTour_SelectedIndexChanged(Object sender, EventArgs e)
{
// Call the method that gets the current item from the dropdown and fills the textboxes
PopulateTextBoxes();
}

Need help figuring out a gridview what am I doing wrong?

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();

Resources