Multiple DataKeyNames in Master Detail Gridview - asp.net

This code lets you search for a table name in an Oracle database. then when you select a row it puts all the columns for the selected table in the second gridview.
The Code below works if I only use one DatakeyName - "Table_Name" but it will display identical table names with different owners if they exist which is not what I want. I want to pull the details based on two fields - Table_Name and Owner.
I can't figure out how to get the details part to work with two datakeyNames.
<asp:Label ID="lblTitleSrchOracleTab" runat="server" Text="Search For A Table In Oracle"></asp:Label>
<br /><br />
<asp:Label ID="lblOracleTableName" runat="server" Text="Oracle Table Name"></asp:Label>
<asp:TextBox ID="txtOracleTableName" runat="server"></asp:TextBox>
<asp:Button ID="btnOracleTableName" runat="server" Text="Search"
/>
<br /><br />
<asp:GridView ID="gvOracleTableName" runat="server" CssClass="mGrid"
AutoGenerateSelectButton="True" AutoGenerateColumns="False"
DataSourceID="sdsOracleTableName" DataKeyNames="Owner,Table_Name" >
<Columns>
<asp:BoundField DataField="OWNER" HeaderText="OWNER" SortExpression="OWNER" />
<asp:BoundField DataField="TABLE_NAME" HeaderText="TABLE_NAME"
SortExpression="TABLE_NAME" />
<asp:BoundField DataField="NUM_ROWS" HeaderText="NUM_ROWS"
SortExpression="NUM_ROWS" />
<asp:BoundField DataField="TABLESPACE_NAME" HeaderText="TABLESPACE_NAME"
SortExpression="TABLESPACE_NAME" />
</Columns>
</asp:GridView>
<asp:SqlDataSource ID="sdsOracleTableName" runat="server"
ConnectionString="<%$ ConnectionStrings:ConnectionString %>"
ProviderName="<%$ ConnectionStrings:ConnectionString.ProviderName %>" SelectCommand="SELECT Owner, Table_name, Num_Rows, Tablespace_name
FROM all_tables
WHERE trim(upper(table_name)) LIKE trim(upper('%' || :TableName || '%'))">
<SelectParameters>
<asp:ControlParameter ControlID="txtOracleTableName" Name="TableName"
PropertyName="Text" />
</SelectParameters>
</asp:SqlDataSource>
<br /><br />
<asp:GridView ID="gvSelectedTableColumns" runat="server" CssClass="mGrid"
AutoGenerateColumns="False" DataSourceID="sdsgvSelectedTableColumns">
<Columns>
<asp:BoundField DataField="OWNER" HeaderText="OWNER" SortExpression="OWNER" />
<asp:BoundField DataField="TABLE_NAME" HeaderText="TABLE_NAME"
SortExpression="TABLE_NAME" />
<asp:BoundField DataField="COLUMN_NAME" HeaderText="COLUMN_NAME"
SortExpression="COLUMN_NAME" />
<asp:BoundField DataField="DATA_TYPE" HeaderText="DATA_TYPE"
SortExpression="DATA_TYPE" />
<asp:BoundField DataField="DATA_LENGTH" HeaderText="DATA_LENGTH"
SortExpression="DATA_LENGTH" />
<asp:BoundField DataField="NULLABLE" HeaderText="NULLABLE"
SortExpression="NULLABLE" />
</Columns>
<SelectedRowStyle BorderColor="Red" Font-Bold="True" />
</asp:GridView>
<asp:SqlDataSource ID="sdsgvSelectedTableColumns" runat="server"
ConnectionString="<%$ ConnectionStrings:ConnectionString %>"
ProviderName="<%$ ConnectionStrings:ConnectionString.ProviderName %>" SelectCommand="SELECT Owner, table_name, column_name, Data_Type, Data_Length, Nullable
FROM all_tab_columns
WHERE trim(upper(Owner)) =trim(upper(:SelectedOwner)) AND
trim(upper(table_name)) =trim(upper(:SelectedTableName))
">
<SelectParameters>
<asp:ControlParameter ControlID="gvOracleTableName" Name="SelectedOwner"
PropertyName="SelectedValue" />
<asp:ControlParameter ControlID="gvOracleTableName" DefaultValue=""
Name="SelectedTableName" PropertyName="SelectedValue" />
</SelectParameters>
</asp:SqlDataSource>

Can't you extend the where clause?
So
from all_tables where ... and owner = 'MYOWNER'
or
select from user_tables instead of all_tables.

that's what this is
WHERE trim(upper(Owner)) =trim(upper(:SelectedOwner)) AND
trim(upper(table_name)) =trim(upper(:SelectedTableName))
my problem is that when you use the sqlDataSource wizard to connect the paramters to the gridview control, it doesn't let you select which datakey of the gridview to bind it to.

I finally figured this one out. You can't Mighty Mouse it - it takes actual code! Specifically the gridview_SelectedIndexChanged event.
Here's how I did it.
protected void gvOracleTableName_SelectedIndexChanged(object sender, EventArgs e)
{
string SelectedOwner;
SelectedOwner = gvOracleTableName.SelectedRow.Cells[1].Text ;
string SelectedTableName;
SelectedTableName = gvOracleTableName.SelectedRow.Cells[2].Text;
lblTest.Text = SelectedOwner + " " + SelectedTableName;
string strConn, strSQL;
strConn = #"";
strSQL = #"SELECT Owner, table_name, column_name, Data_Type, Data_Length, Nullable FROM all_tab_columns WHERE trim(upper(Owner)) =trim(upper(:SelectedOwner)) AND trim(upper(table_name)) =trim(upper(:SelectedTableName))";
using (OracleConnection cn = new OracleConnection(strConn))
{
OracleCommand cmd = new OracleCommand(strSQL, cn);
cmd.Parameters.AddWithValue(":SelectedOwner", SelectedOwner);
cmd.Parameters.AddWithValue(":SelectedTableName", SelectedTableName);
cn.Open();
OracleDataReader rdr = cmd.ExecuteReader();
gvSelectedTableColumns.DataSource = rdr;
gvSelectedTableColumns.DataBind();
cn.Close();
}
}

Related

Filling GridView Based on DropDownList selected Value (vb.net)

I have a drop down list that has inventory material groups, and I would like there to be a way that when I select a different group, the grid view loads the materials for that group. I'm a little confused on how to accomplish this...
ASPX
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:Design_Construction_V2ConnectionString %>" ProviderName="<%$ ConnectionStrings:Design_Construction_V2ConnectionString.ProviderName %>" SelectCommand="SELECT [UnitPriceInfo], [groupNumber], [itemDescription], [CrossTieType], [AFEFunctionCode], [AFECode], [unitType], [unitPrice] FROM [itemsList_]" FilterExpression="groupNumber = {0}">
<FilterParameters>
<asp:ControlParameter Name="groupNumber" ControlID="ddlMaterials" PropertyName="SelectedValue" Type="Int32" DefaultValue="" />
</FilterParameters>
</asp:SqlDataSource>
<asp:DropDownList runat="server" ID="ddlMaterials"></asp:DropDownList>
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataSourceID="SqlDataSource1" EmptyDataText="There are no data records to display.">
<Columns>
<asp:BoundField DataField="UnitPriceInfo" HeaderText="UnitPriceInfo" SortExpression="UnitPriceInfo" />
<asp:BoundField DataField="groupNumber" HeaderText="groupNumber" SortExpression="groupNumber" />
<asp:BoundField DataField="itemDescription" HeaderText="itemDescription" SortExpression="itemDescription" />
<asp:BoundField DataField="CrossTieType" HeaderText="CrossTieType" SortExpression="CrossTieType" />
<asp:BoundField DataField="AFEFunctionCode" HeaderText="AFEFunctionCode" SortExpression="AFEFunctionCode" />
<asp:BoundField DataField="AFECode" HeaderText="AFECode" SortExpression="AFECode" />
<asp:BoundField DataField="unitType" HeaderText="unitType" SortExpression="unitType" />
<asp:BoundField DataField="unitPrice" HeaderText="unitPrice" SortExpression="unitPrice" />
</Columns>
</asp:GridView>
CODEBEHIND
Private Sub ddlMaterials_Load(sender As Object, e As EventArgs) Handles ddlMaterials.Load
If Not IsPostBack Then
Dim db As New DesignConstructionDataContext
Dim materials = (From m In db.Estimate_Groups
Where (m.BigGroup = "Materials")
Select m.groupName)
ddlMaterials.DataSource = materials
ddlMaterials.DataBind()
End If
End Sub
Private Sub ddlMaterials_SelectedIndexChanged(sender As Object, e As EventArgs) Handles ddlMaterials.SelectedIndexChanged
End Sub
Change FilterParameters to SelectParameters. In where clause use this - where groupNumber = #groupNumber. So changed aspx will be like following.
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:Design_Construction_V2ConnectionString %>" ProviderName="<%$ ConnectionStrings:Design_Construction_V2ConnectionString.ProviderName %>" SelectCommand="SELECT [UnitPriceInfo], [groupNumber], [itemDescription], [CrossTieType], [AFEFunctionCode], [AFECode], [unitType], [unitPrice] FROM [itemsList_] where groupNumber = #groupNumber">
<SelectParameters>
<asp:ControlParameter Name="groupNumber" ControlID="ddlMaterials" PropertyName="SelectedValue" Type="Int32" DefaultValue="" />
</SelectParameters>
</asp:SqlDataSource>

Can I access different controls inside other formview controls?

I have several forms, each with their own DDL, that I'm using inside a page. I have them in different forms because I need different data sources for each DDL. When I press the Submit button, it gives me an error that it can't find the control "ddlCategory". I assume it is because it is in a different formview control. Here is the markup:
<asp:FormView ID="FormView1" runat="server" DataKeyNames="ID"
DataSourceID="AccessDataSource1" DefaultMode="Insert" >
<InsertItemTemplate>
Select a Category:<br />
<asp:DropDownList ID="ddlCategory" runat="server" AutoPostBack="True"
DataSourceID="AccessDataSource1" DataTextField="ORG_NAME"
DataValueField="ID">
</asp:DropDownList>
</InsertItemTemplate>
</asp:FormView>
<asp:AccessDataSource ID="AccessDataSource1" runat="server"
DataFile="~/App_Data/webvideos.mdb"
SelectCommand="SELECT * FROM [ORGANIZATIONS]"/>
<br />
<asp:FormView ID="FormView2" runat="server" DataKeyNames="ID"
DataSourceID="AccessDataSource2" DefaultMode="Insert" >
<InsertItemTemplate>
Select an Organization:<br />
<asp:DropDownList ID="ddlOrg" runat="server"
DataSourceID="AccessDataSource2" DataTextField="SectionName"
DataValueField="ID">
</asp:DropDownList>
</InsertItemTemplate>
</asp:FormView>
<asp:AccessDataSource ID="AccessDataSource2" runat="server"
DataFile="~/App_Data/webvideos.mdb"
SelectCommand="SELECT ID,SectionName FROM ORG_SECTIONS WHERE OrgID=#OrgID ">
<SelectParameters>
<asp:ControlParameter ControlID="ddlCategory"
PropertyName="SelectedValue"
Name="ID" Type="String"
DefaultValue="" />
</SelectParameters>
</asp:AccessDataSource>
<br />
<asp:FormView ID="FormView3" runat="server" DataKeyNames="ID"
DataSourceID="AccessDataSource3" DefaultMode="Insert" >
<InsertItemTemplate>
Select an Attorney:<br />
<asp:DropDownList ID="ddlAtty" runat="server"
DataSourceID="AccessDataSource3" DataTextField="Expr1" DataValueField="ATTY_ID">
</asp:DropDownList>
</InsertItemTemplate>
</asp:FormView>
<asp:AccessDataSource ID="AccessDataSource3" runat="server"
DataFile="~/App_Data/webvideos.mdb"
SelectCommand="SELECT ATTY_ID, NAME & ' ' & INITIAL & ' ' & LASTNAME AS Expr1 FROM ATTORNEYS ORDER BY NAME & INITIAL & ' ' & LASTNAME">
</asp:AccessDataSource>
Here is the code behind:
protected void AddRec(object sender, EventArgs e)
{
DropDownList ddlCategory = (DropDownList)FormView1.FindControl("ddlCategory");
DropDownList ddlOrg = (DropDownList)FormView2.FindControl("ddlOrg");
DropDownList ddlAtty = (DropDownList)FormView3.FindControl("ddlAtty");
string constr = #"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=|DataDirectory|\webvideos.mdb;";
string cmdstr = "INSERT INTO [Org_Sec_Atty] ([OrgID], [SecID], [AttyID]) VALUES (?, ?, ?)";
OleDbConnection con = new OleDbConnection(constr);
OleDbCommand com = new OleDbCommand(cmdstr, con);
con.Open();
com.Parameters.AddWithValue("#OrgID", ddlCategory.SelectedValue);
com.Parameters.AddWithValue("#SecID", ddlOrg.SelectedValue);
com.Parameters.AddWithValue("#AttyID", ddlAtty.SelectedValue);
com.ExecuteNonQuery();
con.Close();
Response.Redirect("ManageProfAffs.aspx");
}
Again, it tells me that it can't find the control ddlCategory. I thought about putting them all in one formview, but how would I make different datasources for each of the dropdown lists? I also tried not having any formview controls at all and just using "this.[ID of the ddl]" but that gave me a null reference value. Any ideas on how to make this work?
Here's how I did it. I ended up putting all the DDLs inside one formview (I didn't realize I could specify different datasources for DDLs within a formview that has its own datasource) and putting the datasource that uses the property to use the value from the previous DDL. Works like a charm now.
<asp:AccessDataSource ID="AccessDataSource1" runat="server"
DataFile="~/App_Data/webvideos.mdb"
SelectCommand="SELECT * FROM [ORGANIZATIONS]"/>
<asp:AccessDataSource ID="AccessDataSource3" runat="server"
DataFile="~/App_Data/webvideos.mdb"
SelectCommand="SELECT ATTY_ID, NAME & ' ' & INITIAL & ' ' & LASTNAME AS Expr1 FROM ATTORNEYS ORDER BY NAME & INITIAL & ' ' & LASTNAME">
</asp:AccessDataSource>
<br />
<asp:FormView ID="FormView1" runat="server" DataKeyNames="ID"
DataSourceID="AccessDataSource1" DefaultMode="Insert" >
<InsertItemTemplate>
Select a Category:<br />
<asp:DropDownList ID="ddlCategory" runat="server" AutoPostBack="True"
DataSourceID="AccessDataSource1" DataTextField="ORG_NAME"
DataValueField="ID">
</asp:DropDownList>
<br />
<asp:AccessDataSource ID="AccessDataSource2" runat="server"
DataFile="~/App_Data/webvideos.mdb"
SelectCommand="SELECT ID,SectionName FROM ORG_SECTIONS WHERE OrgID=#OrgID ">
<SelectParameters>
<asp:ControlParameter ControlID="ddlCategory"
PropertyName="SelectedValue"
Name="ID" Type="String"
DefaultValue="" />
</SelectParameters>
</asp:AccessDataSource>
Select an Organization:<br />
<asp:DropDownList ID="ddlOrg" runat="server"
DataSourceID="AccessDataSource2" DataTextField="SectionName"
DataValueField="ID">
</asp:DropDownList>
<br />
Select an Attorney:<br />
<asp:DropDownList ID="ddlAtty" runat="server"
DataSourceID="AccessDataSource3" DataTextField="Expr1" DataValueField="ATTY_ID">
</asp:DropDownList>
</InsertItemTemplate>
</asp:FormView>
<br />
<asp:Button ID="Button1" runat="server" Text="Submit" OnClick="AddRec" />
And the code behind:
protected void AddRec(object sender, EventArgs e)
{
DropDownList ddlCategory = (DropDownList)FormView1.FindControl("ddlCategory");
DropDownList ddlOrg = (DropDownList)FormView1.FindControl("ddlOrg");
DropDownList ddlAtty = (DropDownList)FormView1.FindControl("ddlAtty");
string constr = #"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=|DataDirectory|\webvideos.mdb;";
string cmdstr = "INSERT INTO [Org_Sec_Atty] ([OrgID], [SecID], [Atty_ID]) VALUES (?, ?, ?)";
OleDbConnection con = new OleDbConnection(constr);
OleDbCommand com = new OleDbCommand(cmdstr, con);
con.Open();
com.Parameters.AddWithValue("#OrgID", ddlCategory.SelectedValue);
com.Parameters.AddWithValue("#SecID", ddlOrg.SelectedValue);
com.Parameters.AddWithValue("#AttyID", ddlAtty.SelectedValue);
com.ExecuteNonQuery();
con.Close();
Response.Redirect("ManageProfAffs.aspx");
}

how to use delete command in grid view for updation

i have 3 web pages. admin,student and teacher. i have used grid view on each of this page.my table is having a column as 'status'.which is having default value 0. I want to update this value to 1 when i click on delete in gridview. I have written following code. But it is not working.pls help.
this is .aspx file code-
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:TEMPRUJUConnectionString %>"
SelectCommand="SELECT * FROM [login] WHERE ([username] = #username)"
DeleteCommand="UPDATE [login] SET [status]= 1 WHERE [id]=#id"
InsertCommand="INSERT INTO [login] ([name], [midname], [surname], [username], [password], [contact], [dob], [email], [address], [occupation], [ltype]) VALUES (#name, #midname, #surname, #username, #password, #contact, #dob, #email, #address, #occupation, #ltype)"
UpdateCommand="UPDATE [login] SET [name] = #name, [midname] = #midname, [surname] = #surname, [username] = #username, [password] = #password, [contact] = #contact, [dob] = #dob, [email] = #email, [address] = #address, [occupation] = #occupation, [ltype] = #ltype WHERE [Id] = #Id">
<DeleteParameters>
<asp:Parameter Name="Id" Type="Int32" />
</DeleteParameters>
and this is my code behind-
protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
SqlConnection con = new SqlConnection("Data Source=SNEHAL-PC\\SNEHAL1;Initial Catalog=TEMPRUJU;Integrated Security=True");
SqlCommand cmd;
SqlDataReader dr;
con.Open();
GridViewRow row = GridView1.Rows[e.RowIndex];
cmd=new SqlCommand("Update login set status=1 where id='" + GridView1.DataKeys[e.RowIndex].Value.ToString() + "'",con);
dr = cmd.ExecuteReader();
}
when you have SqlDataSource you have no need to implement GridView1_RowDeleting,
first you must tell to SqlDataSource that where it can find the value of delete command parametr(s), in your case #id... for this, you need to set DataKeyNames property on your GridView by database unique key field name, in your case id...
<asp:GridView ID="GridView1" runat="server" DataKeyNames="ID" DataSourceID="SqlDataSource1">
then, to set delete command parameter on SqlDataSource you must tell that, find value of #id from SelectedDataKey property, from GridView like this:
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:TEMPRUJUConnectionString %>"
DeleteCommand="UPDATE [login] SET [status]= 1 WHERE [id]=#id">
<DeleteParameters>
<asp:ControlParameter ControlID="GridView1" Name="id" PropertyName="SelectedDataKey" />
</DeleteParameters>
</asp:SqlDataSource>
and finaly, you need to, send a Delete command with your gridView, for this, you can enable deleteing on gridview control to add this <asp:CommandField ShowDeleteButton="True" /> into your grid view markup, or you can convert this field into a TemplateFiled and create your own template with any control _which have_ CommandName property, and set that property (CommandName) to keyword Delete like this :
<asp:LinkButton ID="LinkButton1" runat="server" CommandName="Delete" Text="Delete me"></asp:LinkButton>
this is a sample with Template Field:
<asp:GridView ID="GridView2" runat="server" DataKeyNames="ID" DataSourceID="SqlDataSource1">
<Columns>
<asp:TemplateField ShowHeader="False">
<ItemTemplate>
<asp:LinkButton ID="LinkButton1" runat="server" CausesValidation="False" CommandName="Delete" Text="Delete"></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="UserID" SortExpression="UserID">
<EditItemTemplate>
<asp:TextBox ID="TextBox1" runat="server" Text='<%# Bind("UserID") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label2" runat="server" Text='<%# Bind("UserID") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Age" SortExpression="Age">
<EditItemTemplate>
<asp:TextBox ID="TextBox2" runat="server" Text='<%# Bind("Age") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label3" runat="server" Text='<%# Bind("Age") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<asp:SqlDataSource ID="SqlDataSource2" runat="server" ConnectionString="<%$ ConnectionStrings:TestConnectionString %>"
DeleteCommand="UPDATE Profiles SET Age = Age+1 where id = #id" SelectCommand="SELECT * FROM Profiles">
<DeleteParameters>
<asp:ControlParameter ControlID="GridView1" Name="id" PropertyName="SelectedDataKey" />
</DeleteParameters>
</asp:SqlDataSource>
and this is a sample with just enable deleteing :
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataKeyNames="ID" DataSourceID="SqlDataSource1">
<Columns>
<asp:CommandField ShowDeleteButton="True" />
<asp:BoundField DataField="ID" HeaderText="ID" ReadOnly="True" SortExpression="ID" />
<asp:BoundField DataField="UserID" HeaderText="UserID" SortExpression="UserID" />
<asp:BoundField DataField="Age" HeaderText="Age" SortExpression="Age" />
</Columns>
</asp:GridView>
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:TestConnectionString %>"
DeleteCommand="UPDATE Profiles SET Age = Age+1 where id = #id" SelectCommand="SELECT * FROM Profiles">
<DeleteParameters>
<asp:ControlParameter ControlID="GridView1" Name="id" PropertyName="SelectedDataKey" />
</DeleteParameters>
</asp:SqlDataSource>
i increment age in my sample by every delete command

Dropdownlist in templatefield - update fails (null value insertion)

I have a gridview. In this i have a templatefield with a DropDownList (DDL in EditItemTemplate mode, label in ItemTemplate mode).
When i hit edit on of of the detailsview's rows i can select any value from the DDL (the DDL is populated from a sqldatasource), but if i try to execute the update, it fails, because it thinks i didn't supply the data...
Here is the exact error (the DB refuse NULL data):
Cannot insert the value NULL into column 'status', table
'gyumolcs.dbo.orders'; column does not allow nulls. UPDATE fails. The
statement has been terminated.
Here is the code for the gridview:
<!-- language: c# -->
<asp:SqlDataSource ID="orderadminSqlDataSource" runat="server"
ConnectionString="<%$ ConnectionStrings:dotnetConnectionString %>"
SelectCommand="SELECT orders.ID, aspnet_Users.UserName, orders.quantity AS Quantity, product.name AS Product, status.name AS Status, orders.date AS Date FROM orders INNER JOIN product ON orders.ordertype = product.ID INNER JOIN status ON orders.status = status.ID INNER JOIN aspnet_Users ON orders.userid = aspnet_Users.UserId ORDER BY date"
DeleteCommand="DELETE FROM orders WHERE (ID = #ID)"
UpdateCommand="UPDATE orders SET status = #status WHERE (ID = #ID)">
<DeleteParameters>
<asp:Parameter Name="ID" />
</DeleteParameters>
<UpdateParameters>
<asp:Parameter Name="status" />
<asp:Parameter Name="ID" />
</UpdateParameters>
</asp:SqlDataSource><asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
DataSourceID="orderadminSqlDataSource" DataKeyNames="ID" Width="608px"
AllowPaging="True" AllowSorting="True" PageSize="15">
<Columns>
<asp:CommandField ShowDeleteButton="True" ShowEditButton="True" />
<asp:BoundField DataField="ID" HeaderText="ID"
SortExpression="ID" InsertVisible="False" ReadOnly="True" >
<ItemStyle HorizontalAlign="Right" />
</asp:BoundField>
<asp:BoundField DataField="UserName" HeaderText="Felhasználónév"
SortExpression="UserName" >
<HeaderStyle HorizontalAlign="Center" />
<ItemStyle HorizontalAlign="Center" />
</asp:BoundField>
<asp:BoundField DataField="Quantity" HeaderText="Mennyiség (kg)"
SortExpression="Quantity" >
<HeaderStyle HorizontalAlign="Center" />
<ItemStyle HorizontalAlign="Center" />
</asp:BoundField>
<asp:BoundField DataField="Product" HeaderText="Termék"
SortExpression="Product" >
<HeaderStyle HorizontalAlign="Center" />
<ItemStyle HorizontalAlign="Center" />
</asp:BoundField>
<asp:TemplateField HeaderText="Rendelés státusz" SortExpression="status">
<EditItemTemplate>
<!--<asp:TextBox ID="TextBox1" runat="server" Text='<%# Bind("Status") %>'></asp:TextBox>-->
<asp:DropDownList ID="DropDownList1" runat="server"
DataSourceID="statustypeDDLSqlDataSource" DataTextField="name"
DataValueField="ID">
</asp:DropDownList>
<asp:SqlDataSource ID="statustypeDDLSqlDataSource" runat="server"
ConnectionString="<%$ ConnectionStrings:dotnetConnectionString %>"
SelectCommand="SELECT [ID], [name] FROM [status]">
</asp:SqlDataSource>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="status" runat="server" Text='<%# Bind("Status") %>'></asp:Label>
</ItemTemplate>
<HeaderStyle HorizontalAlign="Center" />
<ItemStyle HorizontalAlign="Center" />
</asp:TemplateField>
<asp:BoundField DataField="Date" HeaderText="Dátum" SortExpression="Date" />
</Columns>
<PagerSettings PageButtonCount="15" Mode="NumericFirstLast" />
</asp:GridView>
And here is the orderadminSqlDataSource's code (the gridview's datasource)
<!-- language: c# -->
<asp:SqlDataSource ID="orderadminSqlDataSource" runat="server"
ConnectionString="<%$ ConnectionStrings:dotnetConnectionString %>"
SelectCommand="SELECT orders.ID, aspnet_Users.UserName, orders.quantity AS Quantity, product.name AS Product, status.name AS Status, orders.date AS Date FROM orders INNER JOIN product ON orders.ordertype = product.ID INNER JOIN status ON orders.status = status.ID INNER JOIN aspnet_Users ON orders.userid = aspnet_Users.UserId ORDER BY date"
DeleteCommand="DELETE FROM orders WHERE (ID = #ID)"
UpdateCommand="UPDATE orders SET status = #status WHERE (ID = #ID)">
<DeleteParameters>
<asp:Parameter Name="ID" />
</DeleteParameters>
<UpdateParameters>
<asp:Parameter Name="status" />
<asp:Parameter Name="ID" />
</UpdateParameters>
</asp:SqlDataSource>
Please help me, i can't figure out the problem.
Thanks in advance!
I think you're forgetting to set the DropDown's SelectedValue property:
<asp:DropDownList ID="DropDownList1"
runat="server"
DataSourceID="statustypeDDLSqlDataSource"
DataTextField="name"
DataValueField="status"
SelectedValue='<%# Bind("status") %>'
AppendDataBoundItems="True" >
Change your code for statustypeDDLSqlDataSource:
<asp:SqlDataSource ID="statustypeDDLSqlDataSource" runat="server"
ConnectionString="<%$ ConnectionStrings:dotnetConnectionString %>"
SelectCommand="SELECT [ID] as status, [name] FROM [status]">
</asp:SqlDataSource>
You can also simplify this ( no parenthesis necessary ):
UPDATE orders SET [status] = #status WHERE [ID] = #ID
Note: I had to rename the ID column in the query so that it conforms with the status parameter you defined here:
<UpdateParameters>
<asp:Parameter Name="status" />
<asp:Parameter Name="ID" />
</UpdateParameters>
My last edit and attempt here :D
After carefully looking at your GridView's SELECT statement I see where the error lies:
SELECT orders.ID,
aspnet_Users.UserName,
orders.quantity AS Quantity,
product.name AS Product,
status.name AS Status,
orders.date AS Date
FROM orders
INNER JOIN product ON
orders.ordertype = product.ID
INNER JOIN status ON orders.status = status.ID
INNER JOIN aspnet_Users ON orders.userid = aspnet_Users.UserId
ORDER BY date
Change it to:
SELECT orders.ID,
aspnet_Users.UserName,
orders.quantity AS Quantity,
product.name AS Product,
status.ID AS status,
status.name AS StatusName,
orders.date AS Date
FROM orders
INNER JOIN product ON
orders.ordertype = product.ID
INNER JOIN status ON orders.status = status.ID
INNER JOIN aspnet_Users ON orders.userid = aspnet_Users.UserId
ORDER BY date
Now you must change this part too:
<ItemTemplate>
<asp:Label ID="status" runat="server" Text='<%# Bind("StatusName") %>'></asp:Label>
</ItemTemplate>
By the way... here's a nice step by step tutorial on this matter:
Walkthrough: Displaying a Drop-Down List While Editing in the GridView Web Server Control

Error trying to filter drop down list with a Gridview field value via a controlparameter

I'm getting the dreaded 'DropDownList1' has a SelectedValue which is invalid because it does not exist in the list of items.
Parameter name: value error when trying to filter a drop down list in a templatefield using one of the other boundfield values (I'm trying to get a list of employees based on their department - i.e. the user can change the employee but only to another member of the same department).
Here's the code:
<asp:GridView ID="Rotas" runat="server" AllowSorting="True"
DataSourceID="SqlDataSource3" AutoGenerateEditButton="True" DataKeyNames="DateFrom,DateTo,DepartmentId"
AutoGenerateColumns="False" OnRowUpdating="Rotas_RowUpdating">
<Columns>
<asp:BoundField DataField="DateFrom" HeaderText="DateFrom" ReadOnly="True"
SortExpression="DateFrom" />
<asp:BoundField DataField="DateTo" HeaderText="DateTo" ReadOnly="True"
SortExpression="DateTo" />
<asp:TemplateField HeaderText="Employee Name" SortExpression="EmployeeName">
<EditItemTemplate>
<asp:DropDownList ID="DropDownList1" runat="server"
DataSourceID="SqlDataSource4" DataTextField="EmployeeName"
DataValueField="EmployeeName" SelectedValue='<%# Bind("EmployeeName") %>'>
</asp:DropDownList>
</EditItemTemplate>
<ItemTemplate>
</asp:DropDownList>
<asp:Label ID="Label1" runat="server" Text='<%# Bind("EmployeeName") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="DepartmentId" HeaderText="DepartmentId"
ReadOnly="True" SortExpression="DepartmentId" />
<asp:BoundField DataField="EmployeeId" HeaderText="EmployeeId" ReadOnly="False"
SortExpression="EmployeeId" />
</Columns>
</asp:GridView>
<asp:SqlDataSource ID="SqlDataSource3" runat="server"
ConnectionString="<%$ ConnectionStrings:OnCallRotaConnectionString %>"
SelectCommand="SELECT r.DateFrom, r.DateTo, e.EmployeeName, e.EmployeeId, r.departmentid
FROM
dbo.[Rota] r INNER JOIN
dbo.[Employee] AS e ON r.EmployeeId = e.EmployeeId
WHERE (r.DateTo >= GETDATE()) "
UpdateCommand="UPDATE [Rota] SET [EmployeeId] = (select employeeid from employee where employeename = #EmployeeName),
[departmentid] = (select departmentid from employee where employeename = #EmployeeName)
WHERE [DateFrom] = #DateFrom AND [DateTo] = #DateTo AND [DepartmentId] = #DepartmentId">
<UpdateParameters>
<asp:Parameter Name="DateTo" Type="DateTime" />
<asp:Parameter Name="DateFrom" Type="DateTime" />
<asp:Parameter Name="DepartmentId" Type="Int16" />
<asp:Parameter Name="EmployeeId" Type="Int16" />
<asp:Parameter Name="EmployeeName" Type="String" />
</UpdateParameters>
</asp:SqlDataSource>
</p>
<asp:SqlDataSource ID="SqlDataSource4" runat="server"
ConnectionString="<%$ ConnectionStrings:OnCallRotaConnectionString %>"
onselecting="SqlDataSource4_Selecting"
SelectCommand="SELECT [EmployeeName] FROM [Employee] where DepartmentId=#DepartmentId"
>
<SelectParameters>
<asp:ControlParameter ControlID="Rotas" Name="DepartmentId"
PropertyName="SelectedValue" Type="Int16" />
</SelectParameters>
</asp:SqlDataSource>
Really can't see what I'm doing wrong. If I don't use the Select Parameter and just a 'select employeename from employee' then the whole list of employees is displayed fine. As soon as I try and use a controlparameter it falls over. Help! :)
Thanks in advance for any assistance offered.
I think the problem is that your SqlDataSource that returns the list of employees for a department isn't returning any rows, and I think this is because the ControlParameter isn't right. Although you've done the right thing by pointing it at the Rotas GridView and the SelectedValue property, there are three fields used in the DataKeyNames property (DateFrom, DateTo, DepartmentId), and I believe you're currently passing the DateFrom value into your query - hence, no results.
What I think you need to use in the PropertyName of the ControlParameter instead of the SelectedValue property of Rotas is the SelectedDataKey - there's details on MSDN here although the demo code there isn't particularly useful. However the important line is:
If you are creating a ControlParameter
object and want to access a key field
other than the first field, use the
indexed SelectedDataKey property in
the PropertyName property of the
ControlParameter object
So from that I think what you need is:
<asp:SqlDataSource ID="SqlDataSource4" runat="server"
ConnectionString="<%$ ConnectionStrings:OnCallRotaConnectionString %>"
onselecting="SqlDataSource4_Selecting"
SelectCommand="SELECT [EmployeeName] FROM [Employee] where DepartmentId=#DepartmentId"
>
<SelectParameters>
<asp:ControlParameter ControlID="Rotas" Name="DepartmentId"
PropertyName="SelectedDataKey[2]" Type="Int16" />
</SelectParameters>
</asp:SqlDataSource>
Without a copy of your data I can't test it, but give it a go and see what you get...

Resources