Asp.net bind datatable to gridview - asp.net

I know how to bind a simple datatable to a gridview, but this is a different scenario (I think). I am calling a class library dll which returns a class. I can say its kind of list.
I will call it like,
Dim demo = New ABCDataTable()
demo = demo.GetTheDataTable(MyConnectionString)
GridView1.DataSource = demo
GridView1.DataBind()
Question: How do I bind this to gridview in a markup file? Which datasource control I have to use?
Update:
I used ObjectDataSource and assigned SelectMethod="GetTheDataTable" and used selectparameter to pass connection string.
I am assigning connection string in the code behind ObjectDataSource1.SelectParameters["connectionString"].DefaultValue = MyConnectionString;
but I am getting an error.

i don't know if it will work but try like this -
<asp:GridView id="GridView1" runat="server"
DataSource='<%# (new ABCDataTable()).GetTheDataTable(ConfigurationManager.ConnectionString["nameofyourconnectionstringInwebconfigfile"])) %>' >
</asp:GridView>

You can use a Hidden control as a select parameter for connectionString.
Make sure the default constructor of the class ABCDataTable does not have any parameters.
If it does, then you could create a static method in another class to make the instance and return the result to ObjectDatasource.

Related

Show data in html from database

I have a select query which is return just one row data. I want to show them some different part of a page, not in a repeater, datalist etc...
I do not use asp:label or somtehing like that, then how can I show them from client side like eval or how can I bind Codebehind and call them from client side in html?
edit:
codebehind:
DataTable dt = new DataTable(); ;
dt = myprocedur.User_Load(Int32.Parse(Session["User_ID"].ToString())).Tables[0];
That I want to bind it something or somewhere in page Load.
Then in HTML:
<div><%#Eval("User_Name") %><div>
Use like that where I want, whithout <asp:blabla runat:server />, what is the way of that?
If is it possible, can you give me some exapmle?
edit2:
c#
public static string getData()
{
return "abcd";
}
html
<div><%getData%></div>
I guess we can use st like that, can we adapt it for data from database or similar way for it?
Use Form View ,
<asp:FormView ID="FormView1" runat="server"
DataSourceID="yourDataSource">
<ItemTemplate>
<%# Eval("User_Name") %>
</ItemTemplate>
</asp:FormView>
You can reference here !
In my example , I use DataSourceID="yourDataSource" , if you want to bind fromView's data source from code behind , you can bind likes
FormView1.DataSource = yourDataSoruse ;
FormView1.DataBind();
Edit
DataTable dt = new DataTable(); ;
dt = myprocedur.User_Load(Int32.Parse(Session["User_ID"].ToString())).Tables[0];
FormView1.DataSource = dt ;
FormView1.DataBind();

How bind single record data to controls in ASP.NET?

Which is the best control/approach in ASP.NET 4 to bind data from single record, which is fetched from sql server? I have some page to display text, so I need labels like title, date of publication, content and so on - single label for each data. Of course I can use ListView or Repeater, but I wonder if there's some other way.
Thanks in advance
You could use the DetailsView, which is designed to display a single record (though it's usually used in a master-details scenario). DetailsView can use SqlDatasource.
Trivial example:
<asp:SqlDataSource id="slqDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:MyConnectionString %>"
SelectCommand="SELECT * FROM Table" />
<asp:DetailsView id="detailsView1" runat="server"
AutoGenerateRows="true" DataKeyNames="Id"
DataSourceID="sqlDataSource1" />
The above example creates a DetailsView based on the SelectCommnad of the SqlDataSource. In the implementation above, since AutoGenerateRows is set to true the control will render the data. However, you can also specify the fields explicitly, and have different fields you can choose from (BoundField, ButtonField, CheckBoxField, etc).
DetailsView Class
sqldatareader is a good one.
you can create a sql-command, and then use the .executereader method. For example:
dim myReader as SqlDatareader
Dim myCommand As New SqlCommand("myStoredProcedure", myConnection)
With myCommand
.CommandType = CommandType.StoredProcedure
With .Parameters
.Clear()
.AddWithValue("myParameter", parametervalue)
End With
End With
Try
myConnection.open
myReader = myCommand.ExecuteReader
While myReader.Read
Me.myTextBox.Text = myReader("fieldname")
Me.myCheckbox.Checked = myReader("fieldname")
End While
Catch ex As Exception
Response.Write(ex.Message)
Finally
myConnection.Close()
End Try
or some such...
You can not bind data to a textfield. However, using a reader like the one listed above creates a WHOLE bunch of unneeded overhead. Why not create a class?
This way you fetch it in your DAL and then do some processing (or conversion) in your BLL.
Be the way I would do it anyways. DataReaders and DataSets should not be used unless you are binding.

How to retrieve value from sqldatasource1 to textbox1 using vb.net?

How to retrieve value from sqldatasource1 to textbox1 using vb.net ?
i have a table with field Employee Id : 1001
I wannna retrive the top1 employee id in textbox1 using sqldatasource1
Something like this may help:
DataView oDataView = new DataView();
oDataView = SqlDataSource1.Select(DataSourceSelectArguments.Empty);
DataRowView dr = oDataView[0];
TextBox1.Text = dr["EmployeeID"].ToString();
I have not tested this code though.
You may also want to read the followings to get more info on SQLDataSource:
http://quickstarts.asp.net/QuickStartv20/aspnet/doc/ctrlref/data/sqldatasource.aspx
http://www.aspfree.com/c/a/ASP.NET/Programming-the-ASPNET-20-SqlDataSource-Control/
http://www.defaultdotaspx.com/Answer.aspx?QuestionType=ASPNET&QuestionID=149
http://www.mikesdotnetting.com/Article/64/Bind-Data-From-a-SqlDataSource-to-a-Label
Hope this helps!
The easiest way is to call the data source's Select() method, pass in the arguments, and the results are returned as an IENumerable.
Otherwise, the only way is put the textbox in a FormView control, and specify the value to bind via Text='<%# Eval("Field") %>' /> and specify the DataSourceID of the form view.
HTH.

Why is My GridView FooterRow Referencing the Wrong Row?

I have a GridView and, using a fairly common method, I'm using a FooterRow and TemplateFields to provide the missing insert ability. So far so good.
The footer contains a TemplateField with a LinkButton to provide the postback that does the insertion. In the handler for the LinkButton's click, the Insert() method is called on the ObjectDataSource that the GridView is bound to. The ObjectDataSource's insert parameters are populated in the handler for its Inserting event. The code for all of this (abridged) looks like this:
Markup:
<asp:GridView ID="gvComplexRates" runat="server" AutoGenerateColumns="False"
DataKeyNames="id" DataSourceID="odsComplexMileageRates"
EnableModelValidation="True" ShowFooter="True">
<Columns>
<asp:TemplateField ShowHeader="False">
:
:
<FooterTemplate>
<asp:LinkButton ID="addLinkButton" runat="server" CausesValidation="false"
CommandName="Insert" Text="Add"></asp:LinkButton>
</FooterTemplate>
</asp:TemplateField>
:
:
</asp:GridView>
Code Behind:
Private Sub gvComplexRates_RowCommand(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewCommandEventArgs) Handles gvComplexRates.RowCommand
Select Case e.CommandName
Case "Insert"
odsComplexMileageRates.Insert()
End Select
End Sub
Private Sub odsComplexMileageRates_Inserting(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.ObjectDataSourceMethodEventArgs) Handles odsComplexMileageRates.Inserting
Dim fuelTypeDropDown As DropDownList = gvComplexRates.FooterRow.FindControl("ddFuelTypeInsert")
Dim engineTypeDropDown As DropDownList = gvComplexRates.FooterRow.FindControl("ddEngineTypeInsert")
Dim rateTextBox As TextBox = gvComplexRates.FooterRow.FindControl("tbRateInsert")
Dim vatRateTextBox As TextBox = gvComplexRates.FooterRow.FindControl("tbVatRateInsert")
e.InputParameters("expense_type_id") = ddExpenseTypeSelect.SelectedValue
e.InputParameters("fuel_type_id") = fuelTypeDropDown.SelectedValue
e.InputParameters("engine_type_id") = engineTypeDropDown.SelectedValue
e.InputParameters("rate") = rateTextBox.Text
e.InputParameters("vat_rate") = vatRateTextBox.Text
End Sub
Two of the fields in my FooterRow are DropDownLists that are populated from other tables. Again this works fine and I can add, edit and remove rows without problem.
The problem comes when I use a modal dialog from this page to insert extra rows into the tables used to populate the DropDownLists in the FooterRow. The insert operations work fine and the modal dialog closes and at this point I use a javascript postback (basically a call to __doPostBack()) so that my FooterRow DropDownLists can be updated. The code for this is:
Protected Sub updateFuelEngineDropdowns()
odsFuelTypes.Select()
odsEngineTypes.Select()
Dim dropDown As DropDownList = gvComplexRates.FooterRow.FindControl("ddFuelTypeInsert")
dropDown.DataBind()
dropDown = gvComplexRates.FooterRow.FindControl("ddEngineTypeInsert")
dropDown.DataBind()
End Sub
This sub, updateFuelEngineDropdowns(), is called from the Page Load event. The first time I called it it worked fine. For some reason in subsequent runs through the debugger I'm getting NullReferenceExceptions. Digging into the debug object viewer it is apparent that the GridView FooterRow is referencing the row above the footer which contains no controls (at least not at this non-editing stage) and so, quite reasonably, gives my the Null reference.
The debug QuickView expressions I use are:
gvComplexRates.FooterRow.Controls(3)
DirectCast(gvComplexRates.FooterRow.Controls(3),System.Web.UI.WebControls.DataControlFieldCell).Controls(1)
The first of these shows a tag of td. Which makes sense. The second shows text of "10" which is the content for the row above the footer.
Does anybody know why this is happening?
Thanks Dan
Where are you "providing the missing insert ability"?
You have to rebuild the footer-controls on every postback, the GridView.RowCreated-Event would be a good place.
Update:
You have to Databind your GridView after you inserted new rows into your Dropdowns' Tables.
Right, this is a bit embarrassing. I gave a little white lie in the original question. By omission rather than a deliberate attempt to mislead. I am not, in fact, using a GridView but a subclass of it that will display rows when the datasource contains no data. This enables the user to insert new rows when the table is empty. This subclass overrides the FooterRow property and, to my shame, it was this that was getting things wrong. So I made two errors here: first I failed to test my GridView subclass properly and second I sought to prevent what I thought would be unnecessary attention on my subclass by not showing its use in the code snippets I included in the question. My bad. Thanks to Tim for taking the time to try and help me.
Dan

ASP Stored Procedure to GridView

I am attempting to use an existing stored procedure to populate a gridview.
First, I execute the stored procedure and use a SqlAdapter to put it into a DataSet. I know this works because DataSet.Tables[0] contains my data. However, when I create a GridView and bind the data to the GridView, nothing is displayed.
Here is the code for binding the GridView:
DataSet ds = Execute_spr();
GridView testGridView = new GridView();
if (ds.Tables.Count > 0)
{
testGridView.DataSource = ds.Tables[0].AsEnumerable();
testGridView.DataBind();
}
and here is the code for my gridview in the .aspx page:
<asp:GridView ID="testGridView" runat = "server" AutoGenerateColumns = "true" />
Any idea what I might be doing incorrectly?
Edit: I have tried the ds.Tables[0] without AsEnumerable() and using .DefaultView
Why are you re-initialising the Gridview in the line
GridView testGridView = new GridView();
Create a protected member in your codebeind called "testGridView", remove the line above, and you might start to get somewhere...

Resources