"Both DataSource and DataSourceID are defined" error using ASP.NET GridView - asp.net

"Both DataSource and DataSourceID are defined on 'grdCommunication'. Remove one definition."
I just got this error today, the code has been working until this afternoon I published the latest version to our server and it broke with that error both locally and on the server. I don't use "DataSourceID", the application reads database queries into a datatable and sets the datatable as the DataSource on the GridViews. I did a search in Visual Studio, searching the entire solution and the string "DataSourceID" does not appear in even 1 line of code in the entire solution. This is the first thing that freaked me out.
I figure it had been working yesterday, so I reverted the code to yesterday's build. The error was still there. I kept going back a build, and still the issue is there. I went back a month, I am still getting the same error. This application was working fine this morning? There has really been no code changes, and no where in the application is the DataSourceID EVER set on any of the gridviews. Has anyone ever seen anything like this at all??
How can I get that error if DataSourceID is never set... and the word "DataSourceID" is not in my solution? I just did a wingrep on the entire tree doing a case insensitive search on datasourceid.... pulled up absolutely nothing. That word is absolutely no where in the entire application.
<asp:GridView ID="grdCommunication" runat="server"
Height="130px" Width="100%"
AllowPaging="true" >
... standard grid view column setup here...
</asp:GridView>
// Code behind.. to set the datasource
DataSet dsActivity = objCompany.GetActivityDetails();
grdCommunication.DataSource = dsActivity;
grdCommunication.DataBind();
// Updated: removed some confusing notes.

Try this:
DataSet dsActivity = objCompany.GetActivityDetails();
grdCommunication.DataSource = dsActivity.Tables[0];
grdCommunication.DataBind();

Holy smoke batman. The Table name was changed causing my Datasource to be no good. But that error message doesn't make any sense in this situation. So technically tsilb's solution will work if I call the table by index instead of by name, so I'll mark his solution as correct.
After reading his post, I tried dsActivity.Tables["Activities"] instead of passing the dataset to the Datasource and the table name to the Datamember, and obviously that didn't work, but If I pass the actual index, which I don't like doing because that index might change, then it is now working. But the messed up part, was that error.. That error was completely off base as to what the problem was. saying that I defined both and to remove one, when in reality, that was not the case. and another really messed up thing, was the table name was only changed to be all upper case... But hey, "Activities" is a different key than "ACTIVITIES".

Replace this code before this grdCommunication.DataSource = dsActivity;
grdCommunication.DataBind();
grdCommunication.DataSourceID="";

tslib is right, don't do:
grdCommunication.DataSourceID = null;
or the string.Empty version. You only use the DataSourceID if you're using a SqlDataSource or ObjectDataSource control for your binding.
It's called "declarative" binding because you're using "declared" controls from on your page. Binding to controls does not require a call to the DataBind() method.
Because you're DataBinding manually (calling grd.DataBind()) you only set the DataSourrce and then call DataBind().

I ran into the same error, but a totally different problem and solution. In my case, I'm using LINQ to SQL to populate some dropdown lists, then caching the results for further page views. Everything would load fine with a clear cache, and then would error out on subsequent page views.
if (Cache["countries"] != null)
{
lbCountries.Items.Clear();
lbCountries.DataValueField = "Code";
lbCountries.DataTextField = "Name";
lbCountries.DataSource = (Cache["countries"]);
lbCountries.DataBind();}
else
{
var lstCountries = from Countries in db_read.Countries orderby Countries.Name select Countries;
lbCountries.Items.Clear();
lbCountries.DataValueField = "Code";
lbCountries.DataTextField = "Name";
lbCountries.DataSource = lstCountries.ToList();
lbCountries.DataBind();
Cache.Add("countries", lstCountries, null, System.Web.Caching.Cache.NoAbsoluteExpiration, new TimeSpan(0, 240, 0), System.Web.Caching.CacheItemPriority.High, null);
}
The issue came from:
Cache.Add("countries", lstCountries, null, System.Web.Caching.Cache.NoAbsoluteExpiration, new TimeSpan(0, 240, 0), System.Web.Caching.CacheItemPriority.High, null);
When it should have been:
Cache.Add("countries", lstCountries.ToList(), null, System.Web.Caching.Cache.NoAbsoluteExpiration, new TimeSpan(0, 240, 0), System.Web.Caching.CacheItemPriority.High, null);

I got this error today, turns out that it had nothing to do with DataSourceID, and had everything to do with the DatasSource itself.
I had a problem in my DatasSource , and instead of getting a DatasSource related error, I got this meaningless error.
Make sure you're DatasSource is good, and this error should go away.

always bind dataset with table index to gridview...
ex. gridgrdCommunication.Table[0]; as metioned above by Tsilb
second way you intentionally write..
gridgrdCommunication.DataSourceID = String.Empty;
gridgrdCommunication.DataSource=ds;
gridgrdCommunication.DataBind();

Check you database structure.... if you are acceding your data throw a dbml file, the table structure in your database it's different of the dbml file structure

If you are using the Object Data Source and want to conditionally reload the grid in code behind you can successfully do this:
Dim datatable As DataTable = dataset.Tables(0)
Dim dataSourceID As String = gvImageFiles.DataSourceID
gvImageFiles.DataSourceID = Nothing
gvImageFiles.DataSource = datatable.DefaultView
gvImageFiles.DataBind()
gvImageFiles.DataSource = Nothing
gvImageFiles.DataSourceID = dataSourceID

You need to chose one way to bind the grid
if it is from code behind means using c# code then remove the datasourceid property from grid view from design view of grid
like this
//you have to make it like this

Please try this:
gvCustomerInvoiceList.DataSourceID = "";
gvCustomerInvoiceList.DataSource = ci_data;
gvCustomerInvoiceList.DataBind();

I got this error today. It turns out that my stored procedure did not return neither any record nor a structure. This was because I had an empty try catch without a raiserror.

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Page.DataBind()
End Sub
Function GetData()
Dim dt As New DataTable
Try
dt.Columns.Add("ROOM_ID", GetType(String))
dt.Columns.Add("SCHED_ID", GetType(String))
dt.Columns.Add("TIME_START", GetType(Date))
dt.Columns.Add("TIME_END", GetType(Date))
Dim dr As DataRow = dt.NewRow
dr("ROOM_ID") = "Indocin"
dr("SCHED_ID") = "David"
dr("TIME_START") = "2018-01-03 09:00:00.000"
dr("TIME_END") = "2018-01-03 12:00:00.000"
dt.Rows.Add(dr)
Catch ex As Exception
MsgBox(ex.ToString)
End Try
Return dt
End Function
and add this to your item DataSource="<%# GetData() %>"

In my case the connection string to the database was not working. Fixing the connection string got rid of this error.

Related

Verify existence of an item in a dropdownlist

How do I check for the existence of an item in a dropdownlist in vb.net?
Here's my not working code:
dim ddlTestDropdown as dropdownlist
ddlTestDropdown = New DropDownList()
If(ddlTestDropdown.Items.FindByValue("42") Is Not nothing)
Console.WriteLine("It's there")
End If
it won't let me compare the returned ListItem to nothing
Update: The error is from saying Is Not the fix is to say:
If(Not ddlTestDropdown.Items.FindByValue("42") Is Nothing)
Alternate answer:
Here's what I found to do this. Like #praythyus tried you need to test for contains, but vb.net only lets you do contains on a listitem. So I combined what I did with what he did and this worked:
Dim SetThisIfExists = ddlTestDropdown.Items.FindByValue("42")
If(ddlTestDropdown.Items.Contains(SetThisIfExists))
ddlTestDropdown.SelectedIndex = ddlTestDropdown.Items.IndexOf(SetThisIfExists)
End If
Sorry for giving C# syntax. Can you try with
as #RS said, you need to fill the ddl after initializing.
if(ddlTestDropdown.Items.Contains("42"))
{
}
Or instead of FindByValue can you use FindByText

Add New Item to Already Bound ListView in ASP Net (Unable to set DataKeys/FieldName)

My overall goal is to add fake/unbound items to a listview control (for final HTML Table output reasons). This is a code behind solution. Users will not be adding items as it will be outputted in a rigid table.
I have looked at several examples and while this is easy for a dropdown it is not for listview.
The code below works without error, but my item is not shown on runtime. I think the class is not setting the item fieldname correctly, but I can't figure out the right syntax to fix it.
ColumnNameAList.DataSource = PeriodDataView
ColumnNameAList.DataBind()
Dim test As New Example1("ColumnNameA")
Dim newItem As New ListViewDataItem(ColumnNameAList.Items.Count, ColumnNameAList.Items.Count)
newItem.DataItem = test
ColumnNameAList.Items.Insert(ColumnNameAList.Items.Count, newItem)
ColumnNameAList.Items.Add(newItem)
Here is the Example1 class that is supposed to set the DataValueField:
Public Class Example1
Public Sub New(ColumnNameA__1 As String)
ColumnNameA = ColumnNameA__1
End Sub
Private m_ColumnNameA As String
Public Property ColumnNameA() As String
Get
Return m_ColumnNameA
End Get
Set(value As String)
m_ColumnNameA = value
End Set
End Property
End Class
This outputs my original datasource list, but not the added item.
<ItemTemplate>
<td>
<%# Eval("ColumnNameA")%>
</td>
</ItemTemplate>
In the end I could only reliably solve this with a codebehind solution.
I made a copy of the original datasource, modified my copy and then databound to it.
Dim MyOriginalTableSource As Data.DataView = DataManager.example()
Dim ModifiedTable As DataTable = MyOriginalTableSource.ToTable
'do stuff here
Mylistbox.DataSource = ModifiedTable
Mylistbox.DataBind()
Won't work for everyone, but in this case it works fine for me.
There could be a couple of issues with the way you are approaching this, including that the ListView is already databound and that you are both adding and inserting the newItem.
When we have a scenario like this, we take one of two approaches:
1) Add the new item to the data source before the source is data bound.
2) Remove databinding and manually create each of the list view items, then add your new item at the beginning or end of the loop.
Another way to do it would be to inject it into the sql.
select col1, col2, col3 from table1 union select '1','2','3'
this would ensure that the item is always added, and asp.net doesn't need to know or care.
You can add this into the sql query or add it from the behind code before binding query. if you are not binding with sql, you can also do this to any list item with LINQ

ASP.NET Page_Load runs twice due to Bitmap.Save

I have created an VB.NET page to record views for ads and will call page from img src.
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs)
Dim insert_number As Integer = 0
Dim ad_id As Integer = 0
If Request.QueryString("adid") Is Nothing Then
ad_id = 0
Else
If Not Integer.TryParse(Request.QueryString("adid"), ad_id) Then
ad_id = 0
End If
End If
Dim connectStr As String = System.Configuration.ConfigurationManager.AppSettings("connectStr").ToString()
Dim myconnection As SqlConnection = New SqlConnection(connectStr)
Dim mySqlCommand As SqlCommand
myconnection.Open()
Try
mySqlCommand = New SqlCommand("sp_record", myconnection)
mySqlCommand.CommandType = CommandType.StoredProcedure
mySqlCommand.Parameters.AddWithValue("#record_id", ad_id)
insert_number = mySqlCommand.ExecuteNonQuery()
Catch ex As Exception
End Try
myconnection.Close()
Dim oBitmap As Bitmap = New Bitmap(1, 1)
Dim oGraphic As Graphics = Graphics.FromImage(oBitmap)
oGraphic.DrawLine(New Pen(Color.Red), 0, 0, 1, 1)
'Response.Clear()
Response.ContentType = "image/gif"
oBitmap.Save(Response.OutputStream, System.Drawing.Imaging.ImageFormat.Gif)
'oBitmap.Dispose()
'oGraphic.Dispose()
End Sub
Unless I comment oBitmap.Save line, the code runs twice and it makes two inserts (store prcoedure runs twice) to Database.
I have tried AutoEventWireup = "true" and "false" at #PAGE. "true" runs code twice, "false" did not do anything (no error) and did not give any output as well.
I have also tried following version of creating 1pixel image output but it did run twice as well (it requires aspcompat=true in #PAGE part):
'Response.ContentType = "image/gif"
'Dim objStream As Object
'objStream = Server.CreateObject("ADODB.Stream")
'objStream.open()
'objStream.type = 1
'objStream.loadfromfile("c:\1pixel.gif")
'Response.BinaryWrite(objStream.read)
Any ideas are welcome.
You may want to do an onload function for the image to see why it's being called a second time. I'm guessing that it's getting loaded somewhere in the preload and then being called (.Save) during the page load as well and that's why you're seeing the double entry.
If you are trying to get unique page loads, you may want to try putting the oBitmap.Save line within a check for postback like this within the page load:
If Page.IsPostback = False Then
'Bitmap Code Here
End If
And see if that fixes it for you.
If you're loading data from a database, you'll want to make sure that it also is within that PostBack check (because a. you're loading the data twice and b. it can cause these double postbacks in some circumstances).
Edit: Wanted to edit code section to include all bitmap code, not just the save.
Not sure about the specifics, but that is a lot of code within in Page_Load function.
Generally, the way I would solve this type of problem is to have some sort of page arguments that you can check for in order to do the correct things. Either add some get/post parameters to the call that you can check for or check things like the Page.IsPostBack.
I realize this is an old post but I had an similar issue where the page was firing twice on the postback. I found several posts sugesting what is being dicusses here. However, what corrected my issue was setting the page directive property AutoEventWireup=false at the page level.
Here is a good article How to use the AutoEventWireup attribute in an ASP.NET Web Form by using Visual C# .NET that helped me solve this.
Hope this helps!
Risho

Using untyped datasets in Crystal Reports

I'm creating a runtime dataset in page load. In this dataset I'm adding columns like that:
CrystalDecisions.CrystalReports.Engine.ReportDocument orpt =
new CrystalDecisions.CrystalReports.Engine.ReportDocument();
DataTable table = new DataTable("DataSet1");
table.Columns.Add("Fname", typeof(System.String));
table.Columns.Add("Lname", typeof(System.String));
table.Columns.Add("Salary", typeof(System.String));
DataRow row = table.NewRow();
row["Fname"] = "Mathew";
row["Lname"] = "Hayden";
row["Salary"] = "5000$";
table.Rows.Add(row);
ds.Tables.Add(table);
orpt.Load(MapPath("CrystalReport3.rpt"));
orpt.SetDataSource(ds.Tables[0]);
CrystalReportViewer1.ReportSource = orpt;
Records are not displayed in CrystalReport3.rpt when I'm going to run the program.
Please tell me how to set these coloums in Crystal Reports 3!
What happens if you move your code from the Page_Load to the Page_Init event handler of the ASP.NET page?
Try to set the AutoDataBind property to "true":
Gets or sets whether automatic data
binding to a report source is used. If
the value is set to True, the
DataBind() method is called after
OnInit() or Page_Init() events.
Another tip: did you try to call the RefreshReport() (or Refresh() in older versions) method of your CrystalReportViewer1 object?
Instead of
orpt.SetDataSource(ds.Tables[0]);
Do
orpt.SetDataSource(ds.Tables["table_name"]);
table_name is the table name you gave for the table

asp.net gridview sort without data rebind

I am trying to make a gridview sortable which uses a stored procedure as a datasource, I would not want it to rerun the query each time to achieve this. How would I get it to work my current code is:
protected override void OnPreRender(EventArgs e)
{
if (!IsPostBack)
{
SqlCommand cmd2 = new SqlCommand("SR_Student_Course_List", new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["RDCV2ConnectionString"].ConnectionString));
try
{
cmd2.CommandType = CommandType.StoredProcedure;
cmd2.CommandTimeout = 120;
cmd2.Parameters.Add("student_id", SqlDbType.Char, 11).Value = student;
cmd2.Connection.Open();
grdCourses.DataSource = cmd2.ExecuteReader();
grdCourses.DataSourceID = string.Empty;
grdCourses.DataBind();
} finally
{
cmd2.Connection.Close();
cmd2.Connection.Dispose();
cmd2.Dispose();
}}}
This code just binds the data when it isn't a postback, the gridview has viewstate enabled. On pressing the column headers a postback happens but no sorting occurs. If anyone has a simple fix for this please let me know or even better an ajax sort which would avoid the postback would be even better. The dataset is relatively small however takes a long time to query which is why I would not like to requery on each sort.
If you are not paging the results, and just doing a read, then something like the jquery tablesorter plugin would be a quick and easy fix. I have used this on tables of up to 1400 rows and works great, although ~> few hundred probably better on slow putas.
If the gridview is editable, then aspnet event/input validation might spit a dummy if you don't go through the proper registration of client scripts etc.
You could try storing the data in view state (or cache).
In your case, I would use a SqlDataAdapter and fill a DataTable. Then, put the DataTable into a Session variable. When the GridView is sorting, check if the Session variable still exists. If it does not, then fill the DataTable again. Finally sort the DataTable using a DataView and rebind the GridView with the DataView.

Resources