i have two gridviews on a webform in asp.net with c# code behind. i also have 3 tables: user, group and usergroup.
one gridview contains a list of groups with two columns: description and a buttonfield. when the user clicks on this buttonfield, the members of the selected group should be displayed in the second gridview.
however, i get an error "must declare scalar variable #GruppenID every time i click the buttonfield. what am i missing here? sorry but i am completely new to asp and sql...
WORKING:
<%# Page Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" CodeBehind="Gruppenverwaltung.aspx.cs" Inherits="WerIstWo.Gruppenverwaltung" %>
<asp:Content ID="content1" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">
<h1>Gruppenverwaltung</h1>
<asp:Panel ID="pnlGruppe" ScrollBars="Both" runat="server">
<asp:Button ID="btnNeueGruppe" Text="Neue Gruppe" runat="server" OnClick="btnNeueGruppe_Click" />
<asp:GridView DataKeyNames="GruppenID" OnRowCommand="grdGruppe_RowCommand" ID="grdGruppe" runat="server" AutoGenerateColumns="False" DataSourceID="SqlDataSource1">
<Columns>
<asp:BoundField DataField="Bezeichnung" HeaderText="Bezeichnung" SortExpression="Bezeichnung" />
<asp:TemplateField HeaderText="Mitglieder anzeigen">
<ItemTemplate>
<asp:Button ID="btnMitgliederAnzeigen" runat="server" Text="Mitglieder anzeigen" CommandName="MitgliederAnzeigen"
CommandArgument='<%# Eval("GruppenID") %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:CommandField HeaderText="Archivieren" ButtonType="Button" ShowDeleteButton="true" />
</Columns>
</asp:GridView>
<asp:SqlDataSource OnSelected="SqlDataSource1_Selected" ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:ConnectionString %>"
SelectCommand="SELECT [Bezeichnung], [GruppenID] FROM [Gruppe] WHERE [Archiviert] != 1"
DeleteCommand="UPDATE Gruppe SET [Archiviert] = 1 WHERE [GruppenID] = #GruppenID">
</asp:SqlDataSource>
<asp:Button ID="btnZurueck" Text="Zurück" runat="server" OnClick="btnZurueck_Click" />
</asp:Panel>
<asp:Panel Visible="false" ID="pnlMitglieder" ScrollBars="Both" runat="server">
<asp:GridView ID="grdBenutzer" runat="server" AutoGenerateColumns="False" DataSourceID="SqlDataSource2">
<Columns>
<asp:BoundField DataField="Vorname" HeaderText="Vorname" SortExpression="Vorname" />
<asp:BoundField DataField="Nachname" HeaderText="Nachname" SortExpression="Nachname" />
<asp:BoundField DataField="Geburtsdatum" HeaderText="Geburtsdatum" SortExpression="Geburtsdatum" />
</Columns>
</asp:GridView>
<asp:SqlDataSource ID="SqlDataSource2" runat="server" ConnectionString="<%$ ConnectionStrings:ConnectionString %>"
SelectCommand="SELECT a.Vorname,
a.Nachname,
a.Geburtsdatum
FROM [Benutzer] a
INNER JOIN [BenutzerGruppe] b
ON a.BenutzerID = b.BenutzerID
INNER JOIN [Gruppe] c
ON b.GruppenID = c.GruppenID
WHERE c.GruppenID = #GruppenID">
<SelectParameters>
<asp:Parameter Name="GruppenID" />
</SelectParameters>
</asp:SqlDataSource>
<asp:Button ID="Button1" Text="Zurück" runat="server" OnClick="Button1_Click" />
</asp:Panel>
</asp:Content>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Data;
using System.Configuration;
namespace WerIstWo
{
public partial class Gruppenverwaltung : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (Session["UserAuthentication"] == null)
{
Response.Redirect("Login.aspx");
}
}
protected void btnZurueck_Click(object sender, EventArgs e)
{
Response.Redirect("Datenverwaltung.aspx");
}
protected void btnNeueGruppe_Click(object sender, EventArgs e)
{
Response.Redirect("NeueGruppe.aspx");
}
protected void grdGruppe_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "MitgliederAnzeigen")
{
string index = e.CommandArgument.ToString();
pnlMitglieder.Visible = true;
pnlGruppe.Visible = false;
SqlDataSource2.SelectParameters["GruppenID"].DefaultValue = index;
grdBenutzer.DataBind();
}
}
protected void Button1_Click(object sender, EventArgs e)
{
pnlMitglieder.Visible = false;
pnlGruppe.Visible = true;
}
protected void SqlDataSource1_Selected(object sender, SqlDataSourceStatusEventArgs e)
{
}
}
}
You must pass SqlDataSource Select Parameter.
As you are new a whole process should be like this as your need
add CommandArgument property in button Field
// <asp:ButtonField ButtonType="Button" CommandArgument="GruppenID" CommandName="MitgliederAnzeigen" Text="Mitglieder anzeigen" />
replace this to
<asp:TemplateField HeaderText="Mitglieder anzeigen">
<ItemTemplate>
<asp:Button ID="btn1" runat="server" Text="Mitglieder anzeigen" CommandName="MitgliederAnzeigen"
CommandArgument='<%# Eval("GruppenID") %>' />
</ItemTemplate>
</asp:TemplateField>
your SqlDataSource2 must be
<asp:SqlDataSource ID="SqlDataSource2" runat="server" ConnectionString="<%$ ConnectionStrings:ConnectionString %>"
SelectCommand="select a.Nachname,
c.GruppenID
FROM [Benutzer] a
INNER JOIN [BenutzerGruppe] b
ON a.BenutzerID = b.BenutzerID
INNER JOIN [Gruppe] c
ON b.GruppenID = c.GruppenID
WHERE c.GruppenID = #GruppenID
">
<SelectParameters>
<asp:Parameter Name="GruppenID" />
</SelectParameters>
</asp:SqlDataSource>
now on row command
if (e.CommandName == "MitgliederAnzeigen")
{
string index = e.CommandArgument.ToString();
pnlMitglieder.Visible = true;
pnlGruppe.Visible = false;
SqlDataSource2.SelectParameters["GruppenID"].DefaultValue = index;
grdBenutzer.DataBind();
}
You need to declare the SQL parameter #GruppenID in SqlDataSource1 for both the SelectCommand and the DeleteCommand, like this:
<asp:SqlDataSource OnSelected="SqlDataSource1_Selected" ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:ConnectionString %>"
SelectCommand="SELECT [Bezeichnung], [GruppenID] FROM [Gruppe] WHERE [Archiviert] != 1"
DeleteCommand="UPDATE Gruppe SET [Archiviert] = 1 WHERE [GruppenID] = #GruppenID">
<SelectParameters>
<asp:Parameter Name="GruppenID" />
</SelectParameters>
<DeleteParameters>
<asp:Parameter Name="GruppenID" />
</DeleteParameters>
</asp:SqlDataSource>
You can then set the values for this parameter like in this thread.
Related
I want to modify items in gridview by update command but in same page i have also a textbox with required validation.
i'm unable to update in gridview when require validation occur in textbox Control
And Source Code here...
<div class="row">
<asp:Button ID="Button1" runat="server" CssClass="btn btn-primary" Text="Add" OnClick="Button1_Click"
ValidationGroup="btn" />
<asp:Button ID="Button2" runat="server" CssClass="btn btn-primary" Text="Reset" OnClick="Button2_Click"
CausesValidation="False" />
<asp:Button ID="Button3" runat="server" CssClass="btn btn-primary" Text="Show" CausesValidation="False"
OnClick="Button3_Click" />
</div>
</form> </div> </div>
<asp:GridView ID="GridView1" runat="server" CssClass="table-hover table-responsive table-condensed table-bordered"
AllowPaging="True" AllowSorting="True" AutoGenerateColumns="False" DataKeyNames="id"
DataSourceID="SqlDataSource1" Visible="False">
<Columns>
<asp:CommandField ShowDeleteButton="True" ShowEditButton="True" />
<asp:BoundField DataField="id" HeaderText="id" InsertVisible="False" ReadOnly="True"
SortExpression="id" />
<asp:BoundField DataField="Loc" HeaderText="Location" SortExpression="Loc" />
</Columns>
</asp:GridView>
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:mycon %>"
SelectCommand="SELECT * FROM [location]" DeleteCommand="Delete From Location Where Id=#id"
UpdateCommand="update location set loc=#loc where id=#id">
<DeleteParameters>
<asp:ControlParameter ControlID="TextBox1" Name="id" PropertyName="Text" />
</DeleteParameters>
<UpdateParameters>
<asp:Parameter Name="loc" />
<asp:ControlParameter ControlID="GridView1" Name="id" PropertyName="SelectedValue" />
</UpdateParameters>
</asp:SqlDataSource>
and cs code here
protected void Button1_Click(object sender, EventArgs e)
{
string qry = "insert into location (loc)values(#loc) ";
SqlConnection con = Connection.Getconnection();
con.Open();
SqlCommand cmd = new SqlCommand(qry, con);
cmd.Parameters.AddWithValue("#loc", TextBox1.Text);
int x = cmd.ExecuteNonQuery();
if (x > 0)
{
ClientScript.RegisterStartupScript(Page.GetType(), "validation!", "<script>alert('Successfully Add')</script>");
}
else
{
ClientScript.RegisterStartupScript(Page.GetType(), "validation!", "<script>alert('Error')</script>");
}
}
protected void Button2_Click(object sender, EventArgs e)
{
TextBox1.Text = string.Empty;
}
protected void Button3_Click(object sender, EventArgs e)
{
GridView1.Visible = true;
}
Please try to add try catch for button1_click to catch Exceptions.
Validation group has an effect only when the value of the CausesValidation property is set to true.and validation group need to specify a value
Please Refer this Link
I am not sure what I am doing wrong but no value is being returned on my grid.
I have the following in my .aspx.cs file:
protected void Page_Load(object sender, EventArgs e)
{
SqlDS1.SelectParameters.Add("#ID", "6");
}
I have the following in my .aspx file
<asp:SqlDataSource ID="SqlDS1" runat="server" ConnectionString="<%$ ConnectionStrings:LisSQL %>"
SelectCommand="select RemediationID, RemediationDate, RemediationUser, RemediationAction from VAPHS_Remediation WHERE ID = #ID">
<SelectParameters>
<asp:Parameter Name="ID" Type="Int32" />
</SelectParameters>
</asp:SqlDataSource>
<asp:GridView ID="GridView1" runat="server" DataSourceID="SqlDS1" Width="1200px" AutoGenerateColumns="False" AllowSorting="True">
<Columns>
<asp:BoundField DataField="RemediationID" HeaderText="RemediationID"/>
<asp:BoundField DataField="RemediationDate" HeaderText="RemediationDate"/>
<asp:BoundField DataField="RemediationUser" HeaderText="RemediationUser"/>
<asp:BoundField DataField="RemediationAction" HeaderText="RemediationAction"/>
</Columns>
</asp:GridView>
Nothing gets returned although there is a record for ID = 6
You want to use DefaultValue instead of add.
protected void Page_Load(object sender, EventArgs e)
{
SqlDS1.SelectParameters["ID"].DefaultValue = "6";
}
You already have declarative parameter already; if you use Add parameter, it'll add another duplicate one.
I have two tables relevant to this question...
tblCellTechnology
CellTechnologyID, PK
Description
CellName
tblActionSchedule
ActionID, PK
ActionPhase
ActionPeriod
CellTechnology, FK
I have a bulk edit grid view with text boxes displaying the ActionID, Phase, Period and a dropdownlist linked directly to the CellTechnologyID from tblCellTechnology (as per image). I also have another textbox displaying the cell name based on the value in tblScheduleAction.CellTechnologyID (ActionDescription is pulled from another table).
How can I get the selected value from the ddl and write that to tblScheduleAction.CellTechnologyID? When I hard add a CellTechnologyID to tblScheduleActionID, the cellname textbox displays the correct value. I just need to be able to store the ddl.SelectedValue to tblScheduleAction.CellTechnologyID. I am using masterpages and sqldatasources to handle the inserting/updating/deleting of records.
I want the celltechnologyid column in the bottom gridview to display the list of potential celltechnologyid, it does as it is directly linked to that column from the top grid view, the selected value should also be stored in tblScheduleAction.CellTechnologyID. The cellname column should display the respective cellname.
As they say, a picture is worth a thousand words... http://imgur.com/21FjOzh
By nested gridviews, I assume you are referring to a child gridview inside each parent gridview row. Getting values of child gridview controls is pretty easy.
How can I get the selected value from the ddl and write that to tblScheduleAction.CellTechnologyID?
You use FindControl to find childgridview in say a foreach loop on your save records
You would then use find control to find the dropdownlists & save to your database
Check working example (Aspx)
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="NestedGridviews.aspx.cs" Inherits="WebApplication1.NestedGridviews" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:GridView ID="gvParent" runat="server" AutoGenerateColumns="False"
DataKeyNames="CategoryID" DataSourceID="sdsParentGrid"
onrowdatabound="GridView1_RowDataBound">
<Columns>
<asp:BoundField DataField="CategoryID" HeaderText="CategoryID"
InsertVisible="False" ReadOnly="True" SortExpression="CategoryID" />
<asp:BoundField DataField="CategoryName" HeaderText="CategoryName"
SortExpression="CategoryName" />
<asp:BoundField DataField="Description" HeaderText="Description"
SortExpression="Description" />
<asp:TemplateField>
<ItemTemplate>
<asp:GridView ID="gvChildGrid" runat="server" AutoGenerateColumns="False"
DataKeyNames="ProductID" DataSourceID="sdsChildGrid">
<Columns>
<asp:BoundField DataField="ProductID" HeaderText="ProductID"
InsertVisible="False" ReadOnly="True" SortExpression="ProductID" />
<asp:BoundField DataField="ProductName" HeaderText="ProductName"
SortExpression="ProductName" />
<asp:BoundField DataField="SupplierID" HeaderText="SupplierID"
SortExpression="SupplierID" />
<asp:BoundField DataField="CategoryID" HeaderText="CategoryID"
SortExpression="CategoryID" />
<asp:CheckBoxField DataField="Discontinued" HeaderText="Discontinued"
SortExpression="Discontinued" />
<asp:TemplateField HeaderText="My DropDown Column">
<ItemTemplate>
<asp:DropDownList ID="ddlTest" runat="server">
<asp:ListItem>Potatoes</asp:ListItem>
<asp:ListItem>Tomatoes</asp:ListItem>
<asp:ListItem>Mangoes</asp:ListItem>
</asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<asp:SqlDataSource ID="sdsChildGrid" runat="server"
ConnectionString="<%$ ConnectionStrings:NorthwindConnectionString %>"
SelectCommand="SELECT [ProductID], [ProductName], [SupplierID], [CategoryID], [Discontinued] FROM [Alphabetical list of products] WHERE ([CategoryID] = #CategoryID)">
<SelectParameters>
<asp:Parameter Name="CategoryID" Type="Int32" />
</SelectParameters>
</asp:SqlDataSource>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<asp:SqlDataSource ID="sdsParentGrid" runat="server"
ConnectionString="<%$ ConnectionStrings:NorthwindConnectionString %>"
SelectCommand="SELECT [CategoryID], [CategoryName], [Description] FROM [Categories] ORDER BY [CategoryName]">
</asp:SqlDataSource>
</div>
<asp:Button ID="btnSave" runat="server" onclick="btnSave_Click"
Text="Save to Database" />
</form>
</body>
</html>
Codebehind
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace WebApplication1
{
public partial class NestedGridviews : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
GridView gvChild = e.Row.FindControl("gvChildGrid") as GridView;
SqlDataSource sdsTemp = e.Row.FindControl("sdsChildGrid") as SqlDataSource;
if (sdsTemp!=null)
{
sdsTemp.SelectParameters[0].DefaultValue = gvParent.DataKeys[e.Row.RowIndex]["CategoryID"].ToString();
if (gvChild != null)
{
gvChild.DataBind();
}
}
}
}
protected void btnSave_Click(object sender, EventArgs e)
{
foreach (GridViewRow growParent in gvParent.Rows)
{
// Find child gridview for each row
GridView gvChild = growParent.FindControl("gvChildGrid") as GridView;
if (gvChild != null)
{
// use a foreach loop to find your control
foreach (GridViewRow growChild in gvChild.Rows)
{
DropDownList ddlTemp = growChild.FindControl("ddlTest") as DropDownList;
if (ddlTemp != null)
{
Response.Write(ddlTemp.SelectedValue.ToString());
}
}
}
}
}
}
}
I have used a gridview and linqdatasourse , the gridview will be fill by a linq-stored procedure after clicking a search button.
I did it like below but my grid view is empty.
It seems LinqDataSource2_Selecting does not work.
Please help what is the problem?
public void LinqDataSource2_Selecting(object sender, LinqDataSourceSelectEventArgs e)
{
_DataContext = new EDMSDataContext();
var subjectFilter = e.WhereParameters["Subject"];
var query = _DataContext.spQuickSearchDoc(subjectFilter);
e.Result = query;
}
protected void btnSearch_Click(object sender, EventArgs e)
{
_DataContext = new EDMSDataContext();
this.LinqDataSource2.WhereParameters["Subject"].DefaultValue = this.txtSearchKeywords.Text;
GridViewDocuments.Visible = false;
GridViewDocuments_Search.Visible = true;
this.GridViewDocuments_Search.DataBind();
}
Stored procedure:
ALTER PROCEDURE [dbo].[spQuickSearchDoc]
#Searchtext varchar(50)=null
AS
select DocId,DocumentNo,Title,Unit
from tblDocuments
where DocumentNo like '%'+#SearchText + '%'
or Title like '%'+#SearchText + '%'
or Unit like '%'+#SearchText + '%'
Gridview:
<asp:GridView ID="GridViewDocuments_Search" runat="server" AutoGenerateColumns=False Visible="False" onrowcommand="GridViewDocuments_Search_RowCommand"
DataKeyNames="DocID" PageSize="100" >
<Columns>
<asp:TemplateField HeaderText = "Details">
<ItemTemplate>
<asp:Button ID ="btn_Show" Text="Details" runat= "server" CommandName= "Details" CommandArgument='<%#
Container.DataItemIndex%>' />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="DocumentNo" HeaderText="DocumentNo" SortExpression="DocumentNo" />
<asp:BoundField DataField="title" HeaderText="Title" SortExpression="title" />
<asp:BoundField DataField="Docid" HeaderText="Docid" Visible="false" />
<asp:CommandField ShowEditButton="True" />
<asp:CommandField ShowDeleteButton="True" />
</Columns>
</asp:GridView>
<asp:LinqDataSource ID="LinqDataSource2" runat="server"
ContextTypeName="EDMSDataContext" OnSelecting="LinqDataSource2_Selecting">
<WhereParameters>
<asp:ControlParameter Name="Subject"
ControlID="txtSearchKeywords"
PropertyName="Text"
Type="String" />
</WhereParameters>
</asp:LinqDataSource>
You need to add DataSourceID to the GridView, as in:
<asp:GridView ID="GridViewDocuments_Search" runat="server"
. . DataSourceID="LinqDataSource2">
Since it's not set, the GridView is being bound to NULL.
In ASP.NET, we like using "child" SqlDataSource inside a bound grid server control (Girdview or ListView).
I've been using this FindControl() approach for years:
C# Codebehind:
protected void gridviewItems_RowDataBound(object sender, GridViewRowEventArgs e)
{
Label labelItemId = (Label)e.Row.FindControl("labelItemId");
}
or like this:
protected void buttonSend_Click(object sender, EventArgs e)
{
Label labelItemId = (Label)((Control)sender).NamingContainer.FindControl("labelItemId");
}
Nothing wrong with it, but I'm quite tired of it and maybe there's a way to do this in .aspx markup?
Something like:
<asp:DropDownList
ID="dropdownItems"
runat="server"
DataSource=<% this.NamingContainer.FindControl("slqdatasourceItems") %>
DataTextField="ItemName"
DataValueField="ItemId" />
Is this possible?
I am not sure what your situation is. Do you have something like this?
namespace WebApplication1
{
public class Person
{
private string name;
public string Name
{
set
{
name = value;
}
get
{
return name;
}
}
public List<Person> GetAll()
{
List<Person> persons = new List<Person>();
Person p1 = new Person();
p1.Name = "John";
persons.Add(p1);
return persons;
}
}
}
<form id="form1" runat="server">
<div>
<asp:GridView runat="server" ID="dataGrid" AutoGenerateColumns="false" DataSourceID="persons">
<Columns>
<asp:BoundField HeaderText="Person Name" DataField="Name" />
<asp:TemplateField>
<ItemTemplate>
<asp:DropDownList runat="server" DataTextField="Name" DataSourceID="persons"></asp:DropDownList>
<asp:ObjectDataSource runat="server" ID="persons" TypeName="WebApplication1.Person" SelectMethod="GetAll"></asp:ObjectDataSource>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<asp:ObjectDataSource runat="server" ID="persons" TypeName="WebApplication1.Person" SelectMethod="GetAll"></asp:ObjectDataSource>
</div>
</form>
This is a web form with a gridview which has a "child" datasource pointing to the class Person and it´s method GetAll. There arise no problems at all. Please post some complete markup with your situation.
Edit
If you have something like this:
<asp:ListView runat="server" ID="lv" DataSourceID="SqlDataSource1">
<LayoutTemplate><div runat="server" id="itemPlaceholder"></div></LayoutTemplate>
<ItemTemplate>
<asp:Label runat="server" Text='<%# Eval("Name") %>'></asp:Label>
<asp:Button runat="server" CommandName="Edit" Text="Edit" />
</ItemTemplate>
<EditItemTemplate>
<asp:Label runat="server" Text='<%# Eval("Name") %>'></asp:Label>
<asp:DropDownList ID="DropDownList1" runat="server" DataTextField="Name" DataSourceID="SqlDataSource1"></asp:DropDownList>
<asp:SqlDataSource id="SqlDataSource1" runat="server" DataSourceMode="DataReader"
ConnectionString="<%$ ConnectionStrings:SqlConnectionString%>" SelectCommand="SELECT Name FROM Person">
</asp:SqlDataSource>
</EditItemTemplate>
</asp:ListView>
<asp:SqlDataSource id="SqlDataSource1" runat="server" DataSourceMode="DataReader"
ConnectionString="<%$ ConnectionStrings:SqlConnectionString%>" SelectCommand="SELECT Name FROM Person">
</asp:SqlDataSource>
you shouldn´t have any problems either. I am here a assuming that you are drawing data from a table named "Person". Please show your special case as this is of course a simple setup.