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...
Related
I am getting started with a basic asp.net gridview control and I just dont seem to be able to make it visible in the web browser at all in an asp.net web application.
Here is what I have just to get myself started off. In the aspx page ...
<asp:GridView ID="myGr" runat="server" BackColor="Aqua" AutoGenerateColumns="True" Width="100%" ViewStateMode="Enabled"></asp:GridView>
In the code behind I have ...
Dim tbl As New DataTable
tbl.Columns.Add("ID", GetType(Int32))
tbl.Columns.Add("Name", GetType(String))
tbl.Columns.Add("Birthday", GetType(Date))
Dim pers As DataRow = tbl.NewRow
pers("ID") = 1
pers("Name") = "Tim"
pers("Birthday") = New Date(1973, 6, 9)
myGr.DataSource = tbl
myGr.DataBind()
Would be great if anyone could give me some basic advice on this control
You need to add the row you inserted to the datatable tbl. Because you haven't done this, the datatable is empty so the Gridview is empty too.
Like that: tbl.Rows.add(pers)
You create row but you do not add it to the table.
You have to add line like that:
tbl.Rows.Add(pers)
I am populating a dropdownlist in the edititemtemplate of a formview using linq to SQL.
I am getting the data with the below code:
Dim wdc As New WeeklyChecksDataContext
Dim mustchk = (From w In wdc.WeeklyChecks
Where w.DateStamp = Request.QueryString(0)
Select w.musterCheck).FirstOrDefault()
When debugging I can see that the value "Issue" is being assigned to the mustchk variable which is correct.
I am then databinding the dropdownlist as below:
cbMusterReport.DataSource = mustchk
cbMusterReport.DataBind()
When running the web page the value "Issue" is databound to the dropdownlist but each letter of the word "Issue" is databound to its own separate item rather than the word "Issue" being databound as the only item in the dropdownlist. Can't work out what I am missing here. Thanks
You need to put the string in a collection. Try this:
cbMusterReport.DataSource = new String(){ mustchk }
cbMusterReport.DataBind()
Sorry, I've worked it out. Can do it like this
cbMusterReport.Items.Insert(0, New ListItem(mustchk, mustchk))
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.
Until now, I was working with VS 2003 and recently migrated to VS 2008. I am facing some peculiar problems.
In Vs 2003,I had a Datagrid, and one of the field was ButtonField(Link button). It was not a template field. The user clicks on the field and some data gets generated.
I have written a code, in Vb, like this, on dg_ItemCommand:
Strid = Ctype(e.commandsource,linkbutton).text
Now i want to use same method,for the gridview (I think datagrid is gridview in 2008). I wrote a code like this on dg_Rowcomand
Private Sub dgSampleCustomer_RowCommand(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewCommandEventArgs) Handles dgSampleCustomer.RowCommand
Try
Dim strid As String
Dim i As Integer
strid = CType(e.CommandSource, LinkButton).Text
...
It is throwing a error.
Unable to cast object of type 'System.Web.UI.WebControls.GridView' to
type 'System.Web.UI.WebControls.ButtonField'.
Can anybody help me out!
It looks like the source of the command is the GridView itself, not the button you are clicking. What you probably want to do is set this value you are looking for in the "CommandArgument" property of the Linkbutton. The markup would look something like this:
<asp:LinkButton ID="myLinkButton" runat="server"
CommandName="MyCommandName"
CommandArgument="MySpecialValue"
Text="Click Me" />
Then in the event you would simply:
' strid = "MySpecialValue"
strid = e.CommandArgument.ToString()
Instead of pulling the ID from the name of the control, you can now easily get it from the command. CommandName is optional in this particular case, but comes in handy if you have multiple buttons on a grid that do different things, such as "Edit" and "Delete". Then you can use the command name to handle each command in their own way in the same event:
If (e.CommandName = "Edit") Then
' Do Some Edit Code
End If
I'm wondering why you are trying to cast the command source to a LinkButton? If you would like to attach or otherwise send some kind of row-specific information to your button handler, you are able to do this with the CommandName and CommandArgument attributes of the ButtonField.
Like:
<asp:Gridview ID="...">
...
<columns>
<asp:buttonfield buttontype="Link"
commandname="Generate"
text="Generate"/>
...
</columns>
</asp:GridView>
This will be retrievable in the event handler by using:
if(e.CommandName=="Generate")
{
// Convert the row index stored in the CommandArgument
// property to an Integer.
string rowIndex = Convert.ToInt32(e.CommandArgument);
...
}
http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.gridview.rowcommand.aspx
UPDATE: (use DataKeys)
Since e.CommandArgument returns a row index, and you want the ID, use the DataKeys collection, first add your ID column to the DataKeyNames collection...
<asp:GridView ... DataKeyNames="ID">
... and then retrieve the values from the DataKeys collection, like:
GridView sourceGridView = (GridView) e.CommandSource;
rowIndex = Convert.ToInt32(e.CommandArgument);
strID = sourceGridView.DataKeys[rowIndex]["ID"];
You can try this in your rowcommand event
Dim index = Convert.ToInt32(e.CommandArgument)
Dim row = dg.Rows(index)
'find your linkbutton in template field (replace "lnkBtn" with your's)
Dim myLinkButton = CType(row.FindControl("lnkBtn"), LinkButton)
Dim strid As String = myLinkButton.Text
Let me know if it helps.
I'm having a problem with the dtaview. I'm dynamically creating new datacolumns, assigning them values, and adding them into my datatable. Before using a filter, this was fine when binding. All values appeared.
However, I have since chosen to reduce returned results by filtering (by letter), and my returned dataview doesn't seem to allow binding with the newly created data columns. I've mined into the filtered view, and can see that the values are present that I need.
I'm trying to avoid putting everything back into a table again after applying the filter. An sql query based on letter is out of the question, as the whole original table is sitting in view state.
Here are some code snippets:
--Firstly create new datacolumn
Dim ICount As System.Data.DataColumn = New System.Data.DataColumn
ICount.DataType = System.Type.GetType("System.String")
ICount.AllowDBNull = True
ICount.ColumnName = "ICount"
register.Columns.Add(ICount)
--integer value is first calculated and then put into the datatable row
row("ICount") = IntegerCount.ToString()
--filtered view is created from datatable (returned from viewstate)
Dim filteredView As New Data.DataView(pTable, FilterExpression, "Surname", Data.DataViewRowState.OriginalRows)
--view is bound
grd.DataSource = filteredView
grd.DataBind()
--Markup
<asp:TemplateField HeaderText ="ICount" SortExpression="ICount">
<ItemTemplate>
<asp:Label ID="IC" runat="server" Text='<%# Bind("ICount") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
All of the non dynamic datacolumns are fine. Mining into both the datatable and the filtered view show values are there.
Any help would be much appreciated!!!
Ok - fixed this.
The problem was that I wasn't using the dataset.
So instead of creating a new view, I should have done the following:
datTable = CType(ViewState("datTable"), System.Data.DataTable)
datSet.Tables.Add(datTable)
datView = datSet.Tables(0).DefaultView
datView.RowFilter = FilterExpression
grd.DataSource = datView
grd.DataBind()
All values are now coming through.