I have two web pages- the first is a GridView and the second is a FormView. I have been able to retrieve the DataKey value from the GridView and pass it to the FormView page. Now I need to use that key value for my selection query. How do I assign that value? Code example would help in C#.
This is my page_load code:
protected void Page_Load(object sender, EventArgs e)
{
string CompanyStr = Server.HtmlEncode(Request.QueryString["param1"]);
string ClientKey = Request.QueryString["param2"];
Label lbl = FormView1.FindControl("CompanyID") as Label;
lbl.Text = CompanyStr;
}
And this is the FormView code:
<asp:FormView ID="FormView1" runat="server" DefaultMode="Insert" DataKeyNames="ClientKey"
DataSourceID="SqlDataSource1" onitemcommand="onItemCommand">
The ClientKey is the variable that needs to be set.
It sounds like you want to use a Select Parameter in your SQLDataSource1 markup (the one referenced in your FormView declaration) to do this. This should work:
<asp:SqlDataSource ID="SQLDataSource1" runat="server"
ConnectionString="Your Connection Strong" SelectCommand="SELECT * FROM [yourTableName] WHERE ClientKey = #ClientKey">
<SelectParameters>
<asp:QueryStringParameter Name="ClientKey" QueryStringField="param2" />
</SelectParameters>
</asp:SqlDataSource>
Notice the WHERE clause in the SelectCommand property. I don't know what the rest of your query looks like, but having that on the end should filter your FormView down to what you want.
This should automatically pull the value from your query string, and your FormView will have the proper record loaded.
Related
Trying to update my DB from the edit/update functionality of a GridView. What ever I try, I can't seem to be working.
How can I update my SQLDatasource using the information entered in the GridView edit textbox?
Here is what I have:
.cs:
DS.UpdateCommand = "UPDATE tbSystems SET Systems = #Systems WHERE id = #id";
DS.Update();
.aspx:
<asp:GridView ID="gv1"
runat="server"
CellPadding="2"
DataKeyNames="id"
AutoGenerateDeleteButton="True"
AutoGenerateEditButton="True"
OnRowDeleting="gv1_RowDeleting"
OnRowDeleted="gv1_RowDeleted"
OnRowUpdating="gv1_RowUpdating" OnRowEditing="gv1_RowEditing" OnRowUpdated="gv1_RowUpdated">
</asp:GridView>
<asp:SqlDataSource ID="DS" runat="server" ConnectionString="<%$ ConnectionStrings:conn %>">
<UpdateParameters>
<asp:Parameter Name="Systems" Type="String" />
</UpdateParameters>
</asp:SqlDataSource>
I get this error:
Must declare the scalar variable "#id".
Shouldn't the id variable be declared already since I have it
declared in the DataKeyNames of the GridView or should I create an update parameter in the SQLDataSource?
How do I get the new value in the textbox of the GridView? This line of code always give the old value regardless in which event (edit event, updating event or updated event) I put it in:
Response.Write(((TextBox)gv1.Rows[e.NewEditIndex].Cells[2].Controls[0]).Text);
How do I manage the #variables?
Your help is greatly appreciated.
You don't need any code to connect a GridView to a SqlDataSource control. Just set the relevant properties on the controls and it will just work:
<asp:GridView ID="gv1" runat="server"
DataSourceID="DS"
DataKeyNames="id"
AutoGenerateDeleteButton="True"
AutoGenerateEditButton="True"
/>
<asp:SqlDataSource ID="DS" runat="server"
ConnectionString="<%$ ConnectionStrings:conn %>"
SelectCommand="SELECT * FROM tbSystems"
UpdateCommand="UPDATE tbSystems SET Systems = #Systems WHERE id = #id"
DeleteCommand="DELETE tbSystems WHERE id = #id"
>
<UpdateParameters>
<asp:Parameter Name="id" Type="Int32" />
<asp:Parameter Name="Systems" Type="String" />
</UpdateParameters>
<DeleteParameters>
<asp:Parameter Name="id" Type="Int32" />
</DeleteParameters>
</asp:SqlDataSource>
The important properties are:
DataSourceID - connects the GridView to the SqlDataSource;
SelectCommand - specifies the SQL command used to fill the GridView;
UpdateCommand - specifies the SQL command used to update a record;
UpdateParameters - defines the parameters passed to the UpdateCommand;
DeleteCommand - specifies the SQL command used to delete a record;
DeleteParameters - defines the parameters passed to the DeleteCommand;
With those properties in place, you can get rid of the event handlers in the code-behind. The data source control will take care of everything for you.
ASP.NET Data-Bound Web Server Controls Overview
Data Source Controls Overview
Thanks to the Naveen and lots of tweeking, I finally got to make it work. Here is how I did it. It may not be the best practices but it works.
Put the SQLDataSource in a Session. I don't knkow if this is the right thing to do, however it is the only way I found to catch the value of the gridview edit textbox.
if (!Page.IsPostBack)
{
DS.SelectCommand = "SELECT * FROM tbSystems";
Session["myDS"] = DS;
BindData();
}
Created a BindData function: (gv1 being my GridView)
private void BindData()
{
gv1.DataSource = Session["myDS"];
gv1.DataBind();
}
In the RowEditing function, I've changed the gv1 edit index to the event new edit index.
protected void gv1_RowEditing(object sender, GridViewEditEventArgs e)
{
gv1.EditIndex = e.NewEditIndex;
//Bind data to the GridView control.
BindData();
And this is the update code.
protected void gv1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
DS.UpdateCommand = "UPDATE tbSystems SET Systems = #Systems WHERE id = #id";
var id = gv1.DataKeys[e.RowIndex]["id"];
var systems = ((TextBox)gv1.Rows[e.RowIndex].Cells[2].Controls[0]).Text;
DS.UpdateParameters.Add("id",id.ToString());
DS.UpdateParameters.Add("Systems",systems);
DS.Update();
gv1.EditIndex = -1;
BindData();
}
Hopefully this will help some of you.
Thanks,
Shouldn't the id variable be declared already since I have it declared
in the DataKeyNames of the GridView or should I create an update
parameter in the SQLDataSource?
No. You must fetch the value like this
var id = GridView1.DataKeys[e.RowIndex]["id"];
How do I get the new value in the textbox of the GridView? This line
of code always give the old value regardless in which event (edit
event, updating event or updated event) I put it in
You should be using the RowUpdating event. MSDN sample code here.
How do I manage the #variables?
var systems = ((TextBox)gv1.Rows[e.RowIndex].Cells[2].Controls[0]).Text;
DS.UpdateParameters.Add("#id", id);
DS.UpdateParameters.Add("#Systems", systems);
I have an ASP.NET GridView which amongst other values binds an ID to one of the columns.
Another one of the columns of this table should contain a list of items, which should be resolved by passing in the ID from the GridView.
To achieve this, I tried nesting the ListView inside the GridView, and passing the ID into the Default Parameter of an ObjectDataSource used by the ListView, but this syntax is not allowed:
<asp:TemplateField HeaderText="columnItems">
<ItemTemplate>
<asp:ListView ID="listOfItems" runat="server" DataSourceID="MyObjectDataSource >
<ItemTemplate>
<asp:LinkButton ID="MyLinkButton" Runat="Server" Text='item'></asp:LinkButton>
</ItemTemplate>
</asp:ListView>
<asp:ObjectDataSource ID="MyObjectDataSource" runat="server"
TypeName="MyTypeName.Whatever" SelectMethod="GetItems">
<SelectParameters>
<asp:Parameter Name="requestId" Type="String" DefaultValue='<%# Eval("ID")'/>
</SelectParameters>
</asp:ObjectDataSource>
</ItemTemplate>
</asp:TemplateField>
</Columns>
So how do I go about passing in the ID so I can get the list of items?
You probably need to do that in the RowDataBound event, get the ID there and then do you DB
then do something like
if(e.Row.RowType != DataControlRowType.DataRow)
{
return;
}
ListView a = (ListView)e.Row.FindControl("listOfItems");
a.datasource = // the result of your db call
a.databind();
Attach a 'OnRowDataBound' event to the GridView control to retrieve the items for the ListView for each row on the GridView (after the GridView has been bound):
e.g. On the ASPX page:
<asp:GridView id="MyGridView" OnRowDataBound="GetItems" ... > ... </asp:GridView>
In the code-behind:
protected void GetItems(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType != DataControlRowType.DataRow)
{
return;
}
// Get the ID from the GridView
var dataRowView = (DataRowView) e.Row.DataItem;
var id = dataRowView["ID"].ToString();
// Bind the supporting documents to the ListView control
var listView = (ListView) e.Row.FindControl("listOfItems");
listView.DataSource = /* Call to database to return a DataSet of items */;
listView.DataBind();
}
(As would be appropriate, I tried editing Tunisiano's post to elaborate on his answer on attaching the event to the GridView and getting the request ID, but SO editors are rejecting it for no good reason. The above code is tested and answers the question exactly).
I have a dropdown list to search by categories.
I need help to bind my gridview at page load, but at the same time, I also have a select command as votes.
I know that there are codes such as Databinding in the pageload event. But for my case, i need to link the select command to a button to update votes. If i databind it, i could not grab the data key names to update my votes counter.
Is there any way to bind the gridview, without removing the DataSourceID in the gridview itself?
My aspx codes are as follow.
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:ConnectionString %>"
SelectCommand="SELECT * FROM [Review] WHERE ([Category] = #Category)">
<SelectParameters>
<asp:ControlParameter ControlID="ddlCat" Name="Category"
PropertyName="SelectedValue" Type="String" />
</SelectParameters>
</asp:SqlDataSource>
<asp:SqlDataSource ID="SqlDataSource2" runat="server"
ConnectionString="<%$ ConnectionStrings:ConnectionString %>"
SelectCommand="SELECT [Category] FROM [ReviewCategory]">
</asp:SqlDataSource>
<asp:DropDownList ID="ddlCat" runat="server"
DataSourceID="SqlDataSource2" DataTextField="Category"
DataValueField="Category" AutoPostBack="True"
onselectedindexchanged="SelectionChange">
</asp:DropDownList>
<asp:GridView ID="GridView1" runat="server" Width="1114px"
Height="272px" AutoGenerateColumns="False" PageSize="5"
DataSourceID="SqlDataSource1" AllowPaging="True" DataKeyNames="ReviewID">
<Columns>
<asp:BoundField DataField="Votes" HeaderText="Votes"
SortExpression="Votes" />
<asp:BoundField DataField="Category" HeaderText="Category"
SortExpression="Category" />
<asp:CommandField SelectText="VOTE as your FAVOURITE!"
ShowSelectButton="True" />
</Columns>
c# code
protected void btnVote_Click(object sender, EventArgs e)
{
int reviewid = Convert.ToInt16(GridView1.SelectedDataKey.Value);
SqlConnection conn = new SqlConnection(#"Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Database.mdf;Integrated Security=True;User Instance=True");
string sqlstmt = "select Votes from Review where ReviewID = '" + reviewid + "'";
SqlCommand comm = new SqlCommand(sqlstmt, conn);
try
{
conn.Open();
SqlDataReader read = comm.ExecuteReader();
if (read.Read())
{
int votes = (int)read["Votes"];
votes += 1;
string updatestatement = "Update Review set Votes= '" + votes + "' Where ReviewID = '" + reviewid + "'";
SqlCommand command = new SqlCommand(updatestatement, conn);
read.Close();
command.ExecuteNonQuery();
}
}
finally {
conn.Close();
GridView1.DataBind();
}
}
protected void SelectionChange(object sender, EventArgs e)
{
int stored = ddlCat.SelectedIndex;
if (stored == 0)
{
SqlDataSource1.SelectCommand = "SELECT * from Review ORDER BY [Votes] DESC ";
}
else { }
}
You should implement the RowCommand event from the GridView. You alredy have the CommandField, so do something like this:
void GridView1_RowCommand(Object sender, GridViewCommandEventArgs e)
{
//
// Get the keys from the selected row
//
LinkButton lnkBtn = (LinkButton)e.CommandSource; //the button
GridViewRow myRow = (GridViewRow)lnkBtn.Parent.Parent; //the row
GridView myGrid = (GridView)sender; // the gridview
int reviewid = Convert.ToInt32(GridView1.DataKeys[myRow.RowIndex].Value); //value of the datakey **strong text**
// If multiple buttons are used in a GridView control, use the
// CommandName property to determine which button was clicked.
// In this case you are pressing the button Select, as ou already
// defined this at the aspx code.
if(e.CommandName=="Select")
{
// Put the logic from btnVote_Click here
}
}
The another way could be implement the SelectIndexChanging or SelectIndexChanged, given that you will use the Select Button to fire the update magic. Here the example with SelectIndexChanging.
void GridView1_SelectedIndexChanging(Object sender, GridViewSelectEventArgs e)
{
// Get the currently selected row. Because the SelectedIndexChanging event
// occurs before the select operation in the GridView control, the
// SelectedRow property cannot be used. Instead, use the Rows collection
// and the NewSelectedIndex property of the e argument passed to this
// event handler.
int reviewid = Convert.ToInt32(GridView1.DataKeys[e.NewSelectedIndex].Value); //value of the datakey **strong text**
// Put the logic from btnVote_Click here
}
Let us look into your requirements one by one:
1.) *Binding GridView at PageLoad with DropDownList:
In this case you need to retrieve the Value selected in dropdownList. Do the below setup to grab the Value from DropDownList
<asp:SqlDataSource ID="SqlDataSource2" runat="server"
ConnectionString="<%$ ConnectionStrings:ConnectionString %>"
SelectCommand="SELECT [Category] FROM [ReviewCategory] where Category=#Category">
<SelectParameters><asp:ControlParameter ControlID="ddlCat" Name="Category"
PropertyName="SelectedValue" /></SelectParameters>
</asp:SqlDataSource>
What is Happenning:
Each time a value is selected in dropdown, Postback will happen( AutoPostback="true").
After the Page.PreRender Event, the DataSource controls [ SqlDatSource here ] performs the required queries and retrieve the data. So the selected DropDownList value will be used by SqlDataSource. Thus there is NO need to worry about changing/manipulating DataSourceID in any way.
2.) "But for my case, i need to link the select command to a button to update votes"
'
In this case you have a Select button inside grid View and a 'vote' button outside GridView but somewhere in your page. So, once you select any row in grid view, click the 'Vote' button. You can access the SelectedRow and Index as usual.
protected void btnVote_Click1(object sender, EventArgs e)
{
int i = CustomersGridView.SelectedIndex;
}
Note that the Click event of 'Vote' button fires before the DataSource controls perform their queries & retrieve data. So once you update the Vote count in btnVote_click event as you are doing currently, there is NO need to Bind data again. This part of your code seems fine to me.
I am new to ASP.NET and currently having problem with dropdownlists in the DetailsView.
Exception error: System.InvalidOperationException: Databinding methods such as Eval(), XPath(), and Bind() can only be used in the context of a databound control.
I have this code my code behind to refresh the list for the dropdownlists in DetailsView
protected void ddlVendor_SelectedIndexChanged
(object sender, EventArgs e)
{
DropDownList ddlVendorBB =
(DropDownList)DetailsView1.FindControl("VendorBUName");
if (ddlVendorBB != null)
{
Response.Write("SelectChanged");
ddlVendorBB.DataBind();
}
}
protected void SqlDataSourceProd_Selecting
(object sender, SqlDataSourceSelectingEventArgs e)
{
DropDownList ddlVendor =
(DropDownList)DetailsView1.FindControl("VendorName");
if (ddlVendor != null)
{
e.Command.Parameters["#VendorID"].Value = ddlVendor.SelectedValue;
}
}
These two dropdownlists in the DetailsView
<EditItemTemplate>
<asp:DropDownList id="VendorName"
datasourceid="VendorSqlDataSource"
AutoPostBack="true"
datatextfield="VendorName"
DataValueField="VendorID"
SelectedValue='<%# Bind("VendorID") %>'
runat="server"
OnSelectedIndexChanged="ddlCategory_SelectedIndexChanged" />
<asp:SqlDataSource ID="VendorSqlDataSource"
ConnectionString="<%$Connectionstrings:ConnectionString%>"
SelectCommand="SELECT VendorID, VendorName from MDF_Vendor"
runat="server">
</asp:SqlDataSource>
</EditItemTemplate>
<EditItemTemplate>
<asp:DropDownList id="VendorBUName"
datasourceid="VendorBUSqlDataSource"
datatextfield="VendorBUName"
DataValueField="VendorBUID"
SelectedValue='<%# Bind("VendorBUID") %>'
runat="server"/>
<asp:SqlDataSource ID="VendorBUSqlDataSource"
runat="server"
ConnectionString="<%$Connectionstrings:ConnectionString%>"
selectcommand="SELECT VendorBUID, VendorBUName
from MDF_VendorBU
Where VendorID = #VendorID"
OnSelecting="SqlDataSourceProd_Selecting">
<SelectParameters>
<asp:Parameter Name="VendorID" Type="Int32" />
</SelectParameters>
</asp:SqlDataSource>
</EditItemTemplate>
Problem is:
If I leave SelectedValue= there, the dropdownlists in Edit mode seletected the correct value in the items listed when I first click Edit, but when I select a new VendorName, it errors "Databining method such as Eval(), Xpath(), and Bind()... ".
Now, if I removed the Selectedvalued for the dropdownlists, it will work for refreshing the VendorBUName when select a new VendorName, but NOT not selected the default VendorID when I click "Edit". It just list the VendorName list without selected the current VendorID one.
Can someone please let me know what wrong in my codes? Thanks!
As the error states, you cannot use Bind where you are trying to use it. You should be able to use the DataBinder though
SelectedValue='<%# DataBinder.Eval (Container.DataItem, "VendorBUID") %>'
Edit: Since binding a value to the SelectedValue with DataBinder didn't work, you can try to set the value when binding data. Provided dataSource is some instance of a class that has a property called VendorBUID, something similar to this might work in
public override void OnLoad(EventArgs e) {
VendorBUName.DataBinding += dataBindDropDown;
}
private void dataBindDropDown(object sender, EventArgs e) {
VendorBUName.SelectedValue = dataSource.VendorBUID;
}
I am using VS2005 C#.
Currently I have a GridView, and I have changed one of my GridView control to my column name Gender, from the default TextBox to a DropDownList, which I gave the ID of the control to GenderList, and it contains 2 values, M and F.
I have a default update statement which is able to update the GridView after edit, which is the following:
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString=
"<%$ ConnectionStrings:SODConnectionString %>" UpdateCommand="UPDATE
[UserMasterData] SET [Name] = #Name, [Age] = #Age, [ContactNo]=#ContactNo,
[Address]=#Address, [Gender]=#Gender"/>
The above UPDATE query works perfectly, and now I have changed my Gender textbox to a dropdownlist, the UPDATE query gave me an error which says:
Must declare the scalar variable "#Gender".
I assume the UPDATE query couldn't find the value from my Gender column.
I tried to modify the UPDATE query to #GenderList, but it did not work as well.
Anyone knows what I should do do the UPDATE query so that my UPDATE query can find the value from my GenderList dropdownlist in my Gender column?
Thank you.
Below is my previous Gender column with a textbox control:
<asp:BoundField HeaderText="Gender"
DataField="Gender"
SortExpression="Gender"></asp:BoundField>
Below is my Gender with the dropdownlist control:
<asp:TemplateField HeaderText="Gender" SortExpression="Gender" >
<EditItemTemplate>
<asp:DropDownList ID="GenderList" runat="server" Width="50px" >
<asp:ListItem>M</asp:ListItem>
<asp:ListItem>F</asp:ListItem>
</asp:DropDownList>
</EditItemTemplate>
<ItemTemplate>
EDIT:
Tried implementing RowDatBound and onRowUpdating:
RowDatBound
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
DataRowView dRowView = (DataRowView)e.Row.DataItem;
if (e.Row.RowType == DataControlRowType.DataRow)
{
if ((e.Row.RowState & DataControlRowState.Edit) > 0)
{
DropDownList genderList= (DropDownList)e.Row.FindControl("GenderList");
genderList.SelectedValue = dRowView[2].ToString();
}
}
}
RowUpdating.aspx.cs
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
DropDownList genderSelect =(DropDownList)GridView1.Rows[e.RowIndex].FindControl("GenderList");
SqlDataSource1.UpdateParameters["Gender"].DefaultValue =
genderSelect.SelectedValue; --> error says not set to an instance of an object
}
If you are using SqlDataSource and updating data via it then all you have to do is to set 2 way binding for the dropdownlist GenderList.
You can set this via the designer or directly in source also
<EditItemTemplate>
<asp:DropDownList ID="GenderList" runat="server"
SelectedValue='<%# Bind("Gender") %>'>
<asp:ListItem>M</asp:ListItem>
<asp:ListItem>F</asp:ListItem>
</asp:DropDownList>
</EditItemTemplate>
notice that here 2 way binding is being used.
you need to use its selected value property, dropdown list is collection of values, but you are assigning a scalar value to your update statements.
You have to check when its in update mode, you need to get selected item value of dropdown list and use that value as parameter for update statements.
Editing with Dropdownlist in gridview
to check its in edit mode or not use like this in RowDataBound Event
if ((e.Row.RowState & DataControlRowState.Edit) > 0)