How to retrieve value from sqldatasource1 to textbox1 using vb.net? - asp.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.

Related

Dropdownlist populated with Linq to SQL not displaying items correctly - VB

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

Asp.net bind datatable to gridview

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.

Gridview Linkbutton Code behind

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.

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.

Error: SelectedValue which is invalid because it does not exist in the list of items

I have a Gridview which binds to an ObjectDataSource (objStudentDetails). In edit/insert mode of the Gridview one of the fields is a DropDownList that gets it's pick list options from a lookup table. I have this DropDownList binding to another ObjectDataSource control (objStateList) which represents the lookup table. It works fine as long as the value in the objStudentDetails ObjectDataSource matches one of the values in the objStateList ObjectDataSource, at least in the case of a non empty string value anyway.
The objStateList has these values (from the stored proc that loads it - ID#6 is an empty string ''):
StateId State
----------- -----
6
4 AL
1 GA
3 KY
2 TN
The objStudentDetails has these values (from the stored proc that loads it):
FirstName LastName State
----------- ---------- -----
tone smith TN
Or it could have this result set (State is an empty string - ''):
FirstName LastName State
----------- ---------- -----
jenny johnson
In the first objStudentDetails resultset the state DropDownList in the EditItemTemplate shows up fine. In the second resultset, however, I get this error:
'ddlEditState' has a SelectedValue which is invalid because it does not exist in the list of items.
Parameter name: value
I would think that since my lookup table has a value with an empty string, that the objStudentDetails value with an empty string for state would match, but something isn't working the way I am expecting it to.
Here is my EditItemTemplate code from the Gridview:
<EditItemTemplate>
<asp:Panel ID="panEditState" runat="server">
<asp:DropDownList ID="ddlEditState" runat="server" CssClass="GridviewDropdownlist"
DataSourceID="objStateList" DataTextField="State" DataValueField="State"
SelectedValue='<%# Bind("State") %>'
Width="50px">
</asp:DropDownList>
</asp:Panel>
</EditItemTemplate>
And the objStateList, which calls a method passing a parameter of which lookup table to query:
<asp:ObjectDataSource ID="objStateList" runat="server" SelectMethod="GetDropdownData" TypeName="AIMLibrary.BLL.DropdownData">
<SelectParameters>
<asp:Parameter Name="itemsToGet" DefaultValue="state" />
</SelectParameters>
</asp:ObjectDataSource>
Any ideas?
Start by setting both DropDownLists' AppendDataBoundItems property to true. Next, add the NULL ListItem by adding the following <asp:ListItem> element to each DropDownList so that the declarative markup looks like:
<asp:DropDownList ID="Categories" runat="server"
DataSourceID="CategoriesDataSource" DataTextField="CategoryName"
DataValueField="CategoryID" SelectedValue='<%# Bind("CategoryID") %>'
AppendDataBoundItems="True">
<asp:ListItem Value="">[nothing selected]</asp:ListItem>
</asp:DropDownList>
I suspect there are many different scenarios that can cause this error. In my case, I had a drop down placed in a template field. The drop down was bound to its own objectdatasource, and its selectedvalue property was bound to a field from the gridview's own (separate) datasource.
Now, with my specific scenario, the problem was a race condition. The gridview's datasource was being populated and bound BEFORE the dropdowns had their turn. This also meant that the dropdowns' selectedvalues were being set BEFORE the dropdowns' items had been created through their own bindings.
I'm sure there's got to be a better solution, but I didn't have much time for research. I disconnected the gridview and the dropdowns from their datasources (meaning, removing the assignments from the designer) and opted bind programmatically. That way, I can explicitly bind the dropdowns so that their items' values will be available when the gridview itself is bound.
So far, so good. Just a few extra lines of code in the Page_Load
AppendDataBoundItems="True"> works but not in all cases. Making dropdownlist inside GridView is still a mystery which Microsoft has to resolve. They say development is ASP is much quicker than PHP. Well this is my third day on this small problem and still have no solution.
OK, since this is a common problem I guess its worth to actually post an answer: After a lot of looking around I've found two solutions - well, one patch and one real one.
Patching:
Set the DDL setting AppendDataBoundItem=true anda add manually one element to the list (i.e. "Please Select" with null value):
< asp:DropDownList ID="DropDownList5 runat="server" AppendDataBoundItems="True" ... >
< asp:ListItem>Please Select< /asp:ListItem>
< /asp:DropDownList>
This seems to work in about 80% of cases. I had a weird situation when I had to upgrade existing (and working) query used by DDL to allow another value of parameter - Query was something similar to SELECT ID, Name from EMPLOYEES where Department =#Department and originally #Department could only be equal to "Planners" and "Workshop" - after adding "Logistics" DDL mysteriously stopped working ONLY for the new value of department.
Proper solution: Bind the DDL during the GridView_RowDataBound event (fount thanks to This article
My parameter is taken as a text from the label (set up somewhere else)
protected void GridView5_RowDataBound(object sender, GridViewRowEventArgs e)
{
//********** this is a workaround for the annoying problem with dropdownlist in gidview without adding new item ************
if (e.Row.RowType == DataControlRowType.DataRow && GridView5.EditIndex == e.Row.RowIndex)
{
DropDownList DropDownList5 = (DropDownList)e.Row.FindControl("DropDownList5");
string query = "SELECT gkey as empID, name FROM [employees] where department=#department";
SqlCommand command = new SqlCommand(query);
command.Parameters.AddWithValue("#department", lblDepartment.Text);
DropDownList5.DataSource = GetData(command);
DropDownList5.DataTextField = "name";
DropDownList5.DataValueField = "empID";
DropDownList5.DataBind();
}
And the GetData method:
private DataTable GetData (SqlCommand cmd)
{
string strConnString = ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString;
using (SqlConnection con = new SqlConnection(strConnString))
{
using (SqlDataAdapter sda = new SqlDataAdapter())
{
cmd.Connection = con;
sda.SelectCommand = cmd;
using (DataTable dt= new DataTable())
{
sda.Fill(dt);
return dt;
}
}
}
}

Resources