How to hide Insert form of gridview when inserting row? - asp.net

I am trying to insert a row in Gridview by using a button and text box outside of the Gridview, and it is working fine. But whenever I am inserting the row, insert form of Gridview is appearing. How to disable this form?
my button:
protected void btnAdd_Click(object sender, EventArgs e)
{
MenuAssignmentGv.AddNewRow();
}
my datasource
<asp:SqlDataSource ID="AttdMenuAssignmentDs" runat="server" ConnectionString='<%$ ConnectionStrings:ConnectionString %>' ProviderName='<%$ ConnectionStrings:ConnectionString.ProviderName %>'
SelectCommand="select mra.RoleAssignmentID, mra.MenuRoleID , mr.MenuRole, mn.MenuName, mn.MenuUrl
from ATTD_MST_MENU mn
inner join ATTD_MST_MENU_ROLE_ASSIGNMENT mra
on mn.MenuID=mra.MenuID
inner join ATTD_MST_MENU_ROLE mr
on mra.MenuRoleID=mr.MenuRoleID
where mra.MenuRoleID=#MenuRoleID"
InsertCommand="INSERT INTO ATTD_MST_MENU_ROLE_ASSIGNMENT(MenuRoleID, MenuID) VALUES (#MenuRoleID, #MenuID)"
<InsertParameters>
<asp:ControlParameter ControlID="ddlRole" PropertyName="Value" Name="MenuRoleID" />
<asp:ControlParameter ControlID="ddlMenu" PropertyName="Value" Name="MenuID" />
</InsertParameters>
<SelectParameters>
<asp:ControlParameter ControlID="ddlRole" PropertyName="Value" Name="MenuRoleID"></asp:ControlParameter>
</SelectParameters>
</asp:SqlDataSource>
whenever i click the button the form always appear, and then the record inserted after I click Update of that form.form appear when inserting new row by clicking button

The ASPxGridView.AddNewRow method does exactly what it should do according to the documentation:
The AddNewRow method switches the ASPxGridView to edit mode and allows
the values of the new row to be edited.
Your task is different - you want to add the new row to the database and make it visible in the ASPxGridView. If you insert a new row to the database before the ASPxGridView.DataBind method is called, the new row will become visible in the ASPxGridView automatically. Alternatively, you can continue using the ASPxGridView API according to the documentation:
To add the new record to the underlying datasource, call the
UpdateEdit method. To initialize row values in code, handle the
InitNewRow event.

Related

Displaying Gridview values outside the grid on rowcommand event without using index of column

I have a grid in which all columns are boundfield and one template field, which is a link button.
On clicking the link button, I need to display the grid column values in to a panel which has textboxes, checkbox etc. I am using a Row_Command event for this.
eg: textboxname.text= grid's name column value
I would like not to use rows(0).cells(0) command. Instead of specifying the row or cell number can I do this in Row_Command event.
Please help!
I think you should just link a DetailsView to the GridView's selected index. This would accomplish exactly what you're trying to do, without all the extra work.
Just handle the SelectedIndexChanged event of the GridView, and point your DetailsView's datasource at the ID of the row you've selected. Or, if you're using an SqlDataSource for the DetailsView, you can just use a ControlParameter pointing to the GridView.
General example: You have a GridView, a DetailsView, and the DetailsView is populated by a SqlDataSource. Then you just set up your SqlDataSource to have a ControlParameter that is linked to the selectedValue of the Gridview:
<asp:GridView ID="yourGridView" runat="server" >
...
</asp:GridView>
<asp:DetailsView ID="yourDetailsview" runat="server" DataSourceID="detailsViewDataSource">
...
</asp:DetailsView>
<asp:SqlDataSource ID="detailsViewDataSource" runat="server" ConnectionString="Your connection string"
SelectCommand="SELECT * FROM yourTable WHERE ID = #ID"
<SelectParameters>
<asp:ControlParameter Name="ID" ControlId="yourGridView" PropertyName="SelectedValue"/>
</SelectParameters>
</asp:SqlDataSource>
If you are not using an SqlDataSource, you need to handle the GridView's SelectedIndexChanged event, and then bind the DetailsView (using the new SelectedValue of your GridView) to the record you need using whatever databinding process you'd like.

Use a DDL to select records in a gridview VB.NET

I've got a simple DDL with values like 1, 2, 3.
I have a Gridview with a BoundField DataField="Cycle"
I want to pick a value from the Drop Down List and I want to update my Gridview to only show the records where Cycle = the picked value.
I'm doing this instead of using a Textbox with a Submit button.
When I have my connection string setup, I can test the query and it works, I just can't get the selected/updated value of the drop down List to change the gridview.
Thanks, Bill
You need to handle the DDL aka ComboBox SelectedIndexChanged event. In that event query your DB fetching the data based on the SelectedItem value.
I found out that I created the gridview before the DDL and that threw me off as the datasource was already setup. I ended up redefining the gridview connection and had as it's control parameter the DDL. With that done when I select a new value the GridView refreshes the query.
<asp:AccessDataSource ID="AccessDataSource1" runat="server"
DataFile="~/FromHost06192012_11/FromHost.mdb"
SelectCommand="SELECT * FROM [Table] WHERE ([Cycle] = ?) ORDER BY [Route]">
<SelectParameters>
<asp:ControlParameter ControlID="**DropDownList1**" DefaultValue="%" Name="Cycle2" PropertyName="SelectedValue" Type="String" />
</SelectParameters>
</asp:AccessDataSource>

GridView and DropDownlist

I have a gridview that when enter to edit mode one of the column change to dropdownlist:
<EditItemTemplate>
<asp:DropDownList ID="DropDownList2" runat="server"
DataSourceID="SqlDataSource1" DataTextField="name" DataValueField="name">
</asp:DropDownList>
</EditItemTemplate>
Now i have a SqlDataSource with update method that define in this aspx file:
<UpdateParameters>
<asp:Parameter Name="name" Type="String" />
<asp:ControlParameter ControlID="DropDownList2" Type="string"
PropertyName="SelectedValue" Name="genre" />
</UpdateParameters>
now i want to get the selected value and insert it but when i press the Update button in the row in the gridview i get this error:
Could not find control 'DropDownList2' in ControlParameter 'genre'
any idea why it happen?
Yes. ControlParameters only work when the DOM can find the control you're referring to that's within the same branch of the GridView. The problem is that Gridviews are a poor way of handling DOM controls because as soon as you go into a "mode" of the GridView like the EDIT mode, the entire DOM structure changes. The DOM by the way, is the Document Object Model. Because it's changed, therefore ASP cannot find the control you're referring to.
I've overcome this by doing one of two things.
First see if it works by simply tailing the control name with the '$' character.
<UpdateParameters>
<asp:Parameter Name="name" Type="String" />
<asp:ControlParameter ControlID="MyGridView$DropDownList2" Type="string"
PropertyName="SelectedValue" Name="genre" />
</UpdateParameters>
This sometimes works if you're lucky.
If not, then you'll need to find the control, get its value and pass it into the SQL parameter programmatically in code behind.
Try something like this (I use C#) ...
protected void MyGridView_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
...
GridViewRow gvRow = (GridViewRow)sender;
DropDownList myDDL = (DropDownList)gvRow.FindControl("DropDownList2");
if (myDDL != null)
{
//assuming your datasource is outside the gridview, you have to find it!
SqlDataSource sds1 = (SqlDataSource)page.FindControl("myDataSource");
if (sds1 != null)
{
sds1.UpdateParameter["genre"].DefaultValue = myDDL.SelectedValue;
... and do your databinding etc
sds1.Update();
}
}
}
I always rely on the client-side code (ASPX) to do most of the work for me, like Bind(), Eval(), etc, but over time you'll realise that to really control your program, you'll have to rely on JavaScript or code behind to do the finer bits. ASP is not always "clever" in doing what you expect it to do.

Double Databinding Cascading DropDownList to two SqlDataSources in a FormView

I have two cascading dropdown lists I'm attempting to bind to two separate SqlDataSources each.
These dropdownlists exist in a FormView's EditItemTemplate. Inside the EditItemTemplate two sqldatasource controls exist that populate the department and the jobname. The DeptID and the JobID are the primary keys in those tables. This creates the "cascading effect" between departments and jobs. When a department is selected, only the jobs associated with that department appear.
This piece is working properly.
<asp:FormView ID="frmProfile" runat="server" DataSourceID="sqlDSProfile"
DataKeyNames="EUID" style="margin-top: 0px">
<EditItemTemplate>
<asp:DropDownList ID="ddlDepartments" runat="server" Width="135px"
DataSourceID="sqlDSDepartments"
DataTextField="Department"
DataValueField="DeptID" AutoPostBack="True"
SelectedValue='<%# Bind("CurrentDeptID") %>'
AppendDataBoundItems="true" >
<asp:ListItem></asp:ListItem>
</asp:DropDownList>
<asp:DropDownList ID="ddlJobNames" runat="server" Width="185px"
DataSourceID="sqlDSJobs" DataTextField="JobName" DataValueField="JobID"
SelectedValue='<%# Bind("CurrentJobID") %>'
AppendDataBoundItems="true" >
<asp:ListItem></asp:ListItem>
</asp:DropDownList>
<asp:SqlDataSource ID="sqlDSDepartments" runat="server"
ConnectionString="<%$ ConnectionStrings:JobsDB %>"
SelectCommand="SELECT tblDepartments.DeptID,
tblDepartments.Department
FROM tblDepartments" />
<asp:SqlDataSource ID="sqlDSJobs" runat="server"
ConnectionString="<%$ ConnectionStrings:JobsDB %>"
SelectCommand="SELECT tblJobs.JobID, tblJobs.JobName FROM tblJobs
INNER JOIN tblDeptsJobs ON tblDeptsJobs.JobID = tblJobs.JobID
WHERE tblDeptsJobs.DeptID = #DeptID" >
<SelectParameters>
<asp:ControlParameter ControlID="ddlDepartments" Name="DeptID"
PropertyName="SelectedValue" />
</SelectParameters>
</asp:SqlDataSource>
</EditItemTemplate>
</asp:FormView>
Outside the formview the SqlDataSource exists that binds all of the information to the Employee table in an update statement. I'm leaving all of the other information in this SqlDataSource even though it's been omitted from the FormView above.
<asp:SqlDataSource ID="sqlDSProfile" runat="server"
ConnectionString="<%$ ConnectionStrings:JobsDB %>"
SelectCommand="SELECT tblEmployee.EUID,
tblEmployee.DateHired,
tblEmployee.LastName,
tblEmployee.HiredLastName,
tblEmployee.FirstName,
tblEmployee.Role,
tblEmployee.JobGrade,
tblEmployee.CurrentDeptID,
tblDepartments.Department,
tblDepartments.DeptID,
tblEmployee.CurrentJobID,
tblJobs.JobName,
tblJobs.JobID,
tblEmployee.CurrentShift,
tblEmployee.JobDate,
tblEmployee.IsDisplaced,
tblEmployee.EligibilityDate
FROM tblEmployee
LEFT OUTER JOIN tblDepartments ON tblEmployee.CurrentDeptID = tblDepartments.DeptID
EFT OUTER JOIN tblJobs ON tblEmployee.CurrentJobID = tblJobs.JobID
WHERE (tblEmployee.EUID = #EUID)"
UpdateCommand="UPDATE [tblEmployee]
SET [tblEmployee].[DateHired] = #DateHired,
[tblEmployee].[LastName] = #LastName,
[tblEmployee].[HiredLastName] = #HiredLastName,
[tblEmployee].[FirstName] = #FirstName,
[tblEmployee].[Role] = #Role,
[tblEmployee].[JobGrade] = #JobGrade,
[tblEmployee].[CurrentDeptID] = #CurrentDeptID,
[tblEmployee].[CurrentJobID] = #CurrentJobID,
[tblEmployee].[CurrentShift] = #CurrentShift,
[tblEmployee].[JobDate] = #JobDate,
[tblEmployee].[IsDisplaced] = #IsDisplaced,
[tblEmployee].[EligibilityDate] = #EligibilityDate
WHERE [tblEmployee].[EUID] = #EUID"
ProviderName="System.Data.SqlClient">
<SelectParameters>
<asp:SessionParameter Name="EUID" SessionField="sProfileEUID" DbType="String" />
</SelectParameters>
<UpdateParameters>
<asp:Parameter Name="DateHired" DbType="Date" />
<asp:Parameter Name="LastName" DbType="String" />
<asp:Parameter Name="HiredLastName" DbType="String" />
<asp:Parameter Name="FirstName" DbType="String" />
<asp:Parameter Name="Role" DbType="String" />
<asp:Parameter Name="JobGrade" DbType="Byte" />
<asp:Parameter Name="CurrentDeptID" DbType="Int32" />
<asp:Parameter Name="CurrentJobID" DbType="Int32" />
<asp:Parameter Name="CurrentShift" DbType="Int32" />
<asp:Parameter Name="JobDate" DbType="Date" />
<asp:Parameter Name="IsDisplaced" DbType="Boolean"/>
<asp:Parameter Name="EligibilityDate" DbType="Date"/>
<asp:SessionParameter Name="EUID" SessionField="sProfileEUID" DbType="String" />
</UpdateParameters>
</asp:SqlDataSource>
The only pieces I can't figure out how to bind are the Departments and the Jobs. Everything else is working. I've tried using the following code in the DropDownList controls...
SelectedValue='<%# Bind("CurrentDeptID") %>'
SelectedValue='<%# Bind("CurrentJobID") %>'
...but these result in errors.
Summary
When the user clicks edit, I need the values in the two dropdownboxes to pull their selectedvalue from the main sqlDSProfile data source, but I need them to be updatable. I've gotten it to the point where I can update and bind the job that an associate belongs to, but because the dropdownlists cascade, when I attempt to change the department the AutoPostBack breaks the binding between sqlDSProfile - CurrentJobID and ddlJobs.
Update
I added tblEmployee.CurrentDeptID and tblEmployee.CurrentJobID to the select statement, and added Bind() statements to the DropDownList controls.
SelectedValue='<%# Bind("CurrentDeptID") %>'
SelectedValue='<%# Bind("CurrentJobID") %>'
The two DropDownLists are now populated with accurate information pulled from the Employee table, showing the department and job that the employee belongs to.
The two DropDownLists are also populated by the two SqlDataSources inside the FormView, giving me options for changing the department and changing the job.
When I change the Job, it works and the employees job is updated.
When I change the Department, it breaks saying DataBinding methods such as Eval(), XPath(), and Bind() can only be used in the context of a databound control.
Close to Done
I removed the data binding from ddlJobs and coded that in the background.
Protected Sub frmProfile_ItemUpdating(sender As Object, e As System.Web.UI.WebControls.FormViewUpdateEventArgs) Handles frmProfile.ItemUpdating
If frmProfile.CurrentMode = FormViewMode.Edit Then
e.NewValues("CurrentJobID") = DirectCast(DirectCast(sender, FormView).FindControl("ddlJobs"), DropDownList).SelectedValue
End If
End Sub
The only piece that's left is building the code for when the ddlDepartments changes.
pseudocode...
' If Item exists in ddlJobs Then
' select item (CurrentJobID)
' else
' select index 0 and make them pick something new
' end if
So Close!
Updated Again
This is the code I've developed to loosely bind this. In the page_load I'm trying to pull the contents of CurrentJobID from sqlDSProfile and check to see if that value exists in ddlJobs. If it does I want to set ddlJobs.SelectedValue = to that CurrentJobID. If it doesn't I want to set the selectedindex to 0 which is a message saying "pick one" or something.
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If frmProfile.CurrentMode = FormViewMode.Edit Then
' Need to determine if the CurrentJobID returned in the select statement
' exists in the ddlJobs dropdownlist. If it does, set that to the
' selectedvalue, if not set it to 0 so the user can select a new job.
Dim ddlJobs As DropDownList = frmProfile.FindControl("ddlJobs")
Dim dvProfile As DataView = sqlDSProfile.Select(DataSourceSelectArguments.Empty)
Dim drvProfile As DataRowView = dvProfile(0)
If ddlJobs.Items.FindByValue(drvProfile("CurrentJobID")) Is DBNull.Value Then
ddlJobs.SelectedIndex = 0
Else
ddlJobs.SelectedValue = drvProfile("CurrentJobID")
End If
End If
End Sub
Its returning a null reference exception on the line where I'm checking for dbnull.value
I had a similar issue and found a very simple resolution, (and in c#). Imagine a database with a table Questions, related to category and subcategory tables (which are also related and constrained). When trying to update existing records asp throws an error. This is the solution that I worked out thanks to the information above from Lucretius et al.
Only databind the parent dropdownlist
Find a way to insert the child dropdown selected value on the update event of the datasource.
As:
protected void odseditquestion_Updating(object sender, ObjectDataSourceMethodEventArgs e)
{
//dynamically assign value from ddlsubcategory to odseditquestion on updating event
//you really should not have to do this
DropDownList ddlsubcategory = (DropDownList)fveditquestion.FindControl("ddlsubcategory");
e.InputParameters["subcatid"] = (ddlsubcategory.SelectedValue);
}
It works on my application. Hope it helps somebody, this one cost me half a day, such is asp!!
The problem can be if tlbEmployee columns in the SqlDSProfile in the update statement and field names used by your controls do not match. Other procedures you've followed are right.
SqlDataSource control expects field names it updates to be similar
with those bound to the controls(fields) inside the DataBound control.
The Solution can be: change all the update Parameters to ControlParameters referencing the right control for each one
Update: Wait, I think the problem is your select statement of the SqlDSProfile should contain: CurrentDeptID and CurrentJobID. Try it:
<asp:SqlDataSource ID="sqlDSProfile" runat="server"
ConnectionString="<%$ ConnectionStrings:JobsDB %>"
SelectCommand="SELECT tblEmployee.EUID,
tblEmployee.DateHired,
tblEmployee.LastName,
tblEmployee.HiredLastName,
tblEmployee.FirstName,
tblEmployee.Role,
tblEmployee.JobGrade,
tblDepartments.Department,
tblJobs.JobName,
tblEmployee.CurrentShift,
tblEmployee.JobDate,
tblEmployee.IsDisplaced,
tblEmployee.EligibilityDate
tblEmployee.CurrentDeptID,
tblEmployee.CurrentJobID
FROM tblEmployee
Advice: Test your code portion by portion.
Try the code without the dropdownlist, Test separately
Add the one drop downlist
Use select * from ... in select queries
Avoid ajax when testing
If you make it
Add portions of code portion after portion
at last use the partial updating (ajax)
I have a working solution now, thanks in part to Nuux and a bunch of online research. The tip about the join statement wasn't relevant, but the tip about including "CurrentJobID" and "CurrentDeptID" in my select query was spot on.
In addition to that I had to rework the controls a little. The two cascading dropdownlists are below. The ddlJobs dropdown list behaves like a normal databound control, but it doesn't have the Bind("CurrentJobID") statement I was trying in my original post.
<asp:DropDownList ID="ddlDepartments" runat="server" Width="185px"
DataSourceID="sqlDSDepartments"
DataTextField="Department"
DataValueField="DeptID"
SelectedValue='<%# Bind("CurrentDeptID") %>'
AppendDataBoundItems="true"
AutoPostBack="True" >
<asp:ListItem Text="--Select One--" Value="" />
</asp:DropDownList>
<asp:DropDownList ID="ddlJobs" runat="server" Width="185px"
DataSourceID="sqlDSJobs"
DataTextField="JobName"
DataValueField="JobID"
AppendDataBoundItems="true"
OnDataBinding="ddlJobs_DataBinding" />
The only thing the custom routine "ddlJobs_DataBinding" is doing is adding "--Select One--" as index 0 in the ddlJobs dropdown. I tried this in several places, like page_load, and the databound event of the formview with no success.
Protected Sub ddlJobs_DataBinding(sender As Object, e As System.EventArgs)
Dim ddlJobs As DropDownList = frmProfile.FindControl("ddlJobs")
Dim liSelectOne As New ListItem("--Select One--", 0)
ddlJobs.Items.Clear()
ddlJobs.Items.Insert(0, liSelectOne)
End Sub
The databound event of the formview frmProfile_DataBound event does do some work though. When the user clicks "edit" on the formview to enter editing mode this ensures that the dropdownlist ddlJobs has the correct job selected by default for the profile in question. If the user hasn't been assigned to a job then it defaults to selectedindex 0 which is "--Select One--" set in custom databinding event just above.
Protected Sub frmProfile_DataBound(sender As Object, e As System.EventArgs) Handles frmProfile.DataBound
If frmProfile.CurrentMode = FormViewMode.Edit Then
Dim ddlJobs As DropDownList = frmProfile.FindControl("ddlJobs")
Dim dvProfile As DataView = sqlDSProfile.Select(DataSourceSelectArguments.Empty)
Dim drProfile As DataRow = dvProfile.Table.Rows(0)
If drProfile("CurrentJobID").ToString() = "" Then
ddlJobs.SelectedIndex = 0
Else
ddlJobs.SelectedValue = drProfile("CurrentJobID").ToString()
End If
End If
End Sub
Finally, if the user selects a new job from ddlJobs, that value has to be fed to the database, which the ItemUpdating event of the formview handles.
Protected Sub frmProfile_ItemUpdating(sender As Object, e As System.Web.UI.WebControls.FormViewUpdateEventArgs) Handles frmProfile.ItemUpdating
If frmProfile.CurrentMode = FormViewMode.Edit Then
Dim ddlJobs As DropDownList = frmProfile.FindControl("ddlJobs")
e.NewValues("CurrentJobID") = ddlJobs.SelectedValue
End If
End Sub
Done!

Grab query results from SqlDataSource and store as string

I have a SQL query that will result in one string. Rather than bind a gridview, listview, etc to it and have a single lonely label inside, I just want to store the string (it'll eventually get used later elsewhere). For the life of me I cannot figure this out.
<asp:SqlDataSource ID="SqlDataSource3" runat="server" ConnectionString="<%$ ConnectionStrings:ConnectionString %>"
SelectCommand="select [title] from [books]
where([Genre]=#Genre)
OnSelected="SqlDataSource3_Selected">
<SelectParameters>
<asp:Parameter Name="Title" Direction="ReturnValue" Type="String" />
<asp:ControlParameter ControlID="DropDownList1" Name="genre"
PropertyName="SelectedValue" />
</SelectParameters>
</asp:SqlDataSource>
protected void SqlDataSource3_Selected(object sender, SqlDataSourceStatusEventArgs e)
{
string sqlreturnString = Convert.ToString(e.Command.Parameters["#Title"].Value);
Label3.Text = sqlreturnString;
}
All this does is spit out '0' when I want it to display the title. If I change ["#Title"] to [1], it'll display the Genre. Right now there are only four books, each with a unique genre.
Add a button and write this code in the handler of button's click.
DataSourceSelectArguments sr = new DataSourceSelectArguments();
DataView dv =(DataView) SqlDataSource3.Select(sr);
if(dv.Count!=0)
Label1.Text = dv[0][0].ToString();
I encountered this same issue also when doing C# and ASP.NET, it would be really nice to have a method that dumps out a string of the text results of the query in a SQLDataSource or an AccessDatasource. Until then, Here is an example of the solution I found that works very well:
AccessDataSource MyDataSource = new AccessDataSource("~/App_Data/MyDB.mdb",
"SELECT Name FROM Employees");
DataView MyView = (DataView) MyDataSource.Select(DataSourceSelectArguments.Empty);
lblResults.Text = MyView[0][1].ToString();
This example will also work with SqlDataSource objects.

Resources