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
Related
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");
}
When i click on EDIT button in Grid, it amke all fields editable and provides two options(Update and Cancel). In this Grid, there are two dropdownlists, 3 calenders and some textboxes. If i click on update then all the textbox values updated in the database, but all other fields(dropdown and calender) values in database is automatically NULL.
Below is the main page GridView code:
<asp:GridView ID="GridView1" runat="server" CellPadding="5" ForeColor="#333333" width="1000px"
GridLines="None" OnPageIndexChanging="gridView_PageIndexChanging"
AllowSorting="True" OnSorting="gridView_Sorting" AutoGenerateColumns="False" OnRowUpdating="GridView1_RowUpdating"
BorderStyle="Outset" CellSpacing="1" Font-Names="Cambria"
Font-Size="Small" AllowPaging="True" ShowFooter="True"
ShowHeaderWhenEmpty="True"
DataSourceID="SqlDataSource1" onselectedindexchanged="GridView1_SelectedIndexChanged"
>
<AlternatingRowStyle BackColor="White" ForeColor="#284775" />
<Columns>
<asp:BoundField DataField="case_number" HeaderText="Case Number"
SortExpression="case_number" />
<asp:BoundField DataField="case_name" HeaderText="Case Name"
SortExpression="case_name" />
<asp:BoundField DataField="Case_Type_Text" HeaderText="Case Type"
SortExpression="Case_Type_Text" />
<asp:TemplateField HeaderText="Case Status" SortExpression="Case_Status_Text">
<EditItemTemplate>
<asp:DropDownList ID="DropDownList3" runat="server"
DataSourceID="SqlDataSource3" DataTextField="Case_Status_Text" DataValueField="Case_Status_Text"
SelectedValue='<%# Bind("Case_Status_Text") %>'>
</asp:DropDownList>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%# Bind("Case_Status_Text") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="assigned_date" HeaderText="Assigned Date"
SortExpression="assigned_date" DataFormatString="{0:d}" />
<asp:BoundField DataField="assigned_to" HeaderText="Assigned To"
SortExpression="assigned_to" />
<asp:TemplateField HeaderText="Date Withdrawn" SortExpression="date_withdrawn">
<EditItemTemplate>
<cc1:DatePicker ID="DatePicker5" runat="server" />
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label4" runat="server"
Text='<%# Bind("date_withdrawn", "{0:d}") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Date Delivered" SortExpression="date_delivered">
<EditItemTemplate>
<cc1:DatePicker ID="DatePicker7" runat="server"
/>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label6" runat="server"
Text='<%# Bind("date_delivered", "{0:d}") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="QC By" SortExpression="qc_by">
<EditItemTemplate>
<asp:DropDownList ID="DropDownList5" runat="server"
DataSourceID="SqlDataSource4" DataTextField="User_Name" DataValueField="User_Name"
SelectedValue='<%# Bind("qc_by") %>'>
</asp:DropDownList>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label2" runat="server" Text='<%# Bind("qc_by") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="QC Date" SortExpression="qc_date">
<EditItemTemplate>
<cc1:DatePicker ID="DatePicker6" runat="server"
/>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label5" runat="server" Text='<%# Bind("qc_date", "{0:d}") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Additional Notes">
<EditItemTemplate>
<asp:TextBox ID="TextBox1" runat="server"
Text='<%# Bind("additional_notes") %>' TextMode="MultiLine"></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label3" runat="server" Text='<%# Bind("additional_notes") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:CommandField ShowEditButton="True" ButtonType="Button"
CausesValidation="False" />
</Columns>
<EditRowStyle BackColor="#999999" />
<FooterStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
<HeaderStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="#284775" ForeColor="White" HorizontalAlign="Center" />
<RowStyle BackColor="#F7F6F3" ForeColor="#333333" />
<SelectedRowStyle BackColor="#E2DED6" Font-Bold="True" ForeColor="#333333" />
<SortedAscendingCellStyle BackColor="#E9E7E2" />
<SortedAscendingHeaderStyle BackColor="#506C8C" />
<SortedDescendingCellStyle BackColor="#FFFDF8" />
<SortedDescendingHeaderStyle BackColor="#6F8DAE" />
</asp:GridView>
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:con %>"
ProviderName="<%$ ConnectionStrings:con.ProviderName %>"
SelectCommand="SELECT * FROM [View_Intakesheet]"
UpdateCommand="UPDATE intakesheet SET case_number = #case_number, case_name=#case_name, Case_Type=#case_type, Case_Status = #case_status, assigned_date = #assigned_date, assigned_to = #assigned_to, date_withdrawn= #date_withdrawn, date_delivered= #date_delivered, qc_by = #qc_by, qc_date=#qc_date, additional_notes = #additional_notes WHERE (case_number = #case_number)">
<UpdateParameters>
<asp:Parameter Name="case_number"/>
<asp:Parameter Name="case_name" />
<asp:Parameter Name="case_type" />
<asp:Parameter Name="case_status" />
<asp:Parameter Name="assigned_date" Type="DateTime" />
<asp:Parameter Name="assigned_to" />
<asp:Parameter Name="date_withdrawn" Type="DateTime" />
<asp:Parameter Name="date_delivered" Type="DateTime" />
<asp:Parameter Name="qc_by" />
<asp:Parameter Name="qc_date" Type="DateTime" />
<asp:Parameter Name="additional_notes" />
</UpdateParameters>
</asp:SqlDataSource>
</td>
</tr>
Below is the Update event::
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
GridViewRow row = (GridViewRow)GridView1.Rows[e.RowIndex];
DropDownList ct = (DropDownList)row.FindControl("case_type");
DropDownList cs = (DropDownList)row.FindControl("case_status");
con.Open();
SqlCommand cmd = new SqlCommand("UPDATE intakesheet SET case_number = #case_number, case_name = #case_name, Case_Type = Case_Type, Case_Status = Case_Status, assigned_date = assigned_date, assigned_to = assigned_to, date_withdrawn= date_withdrawn, date_delivered= date_delivered, qc_by = qc_by, qc_date=qc_date, additional_notes = additional_notes WHERE (case_number = case_number)", immigration);
cmd.ExecuteNonQuery();
GridView1.EditIndex = -1;
con.Close();
bind();
}
public void bind()
{
con.Open();
SqlDataAdapter da = new SqlDataAdapter("select * from intakesheet", con);
DataSet ds = new DataSet();
da.Fill(ds, "intakesheet");
//GridView1.DataSource = ds.Tables[0].DefaultView;
GridView1.DataBind();
con.Close();
}
SqlCommand cmd = new SqlCommand("UPDATE intakesheet SET case_number = #case_number, case_name = #case_name, Case_Type = Case_Type, Case_Status = Case_Status, assigned_date = assigned_date, assigned_to = assigned_to, date_withdrawn= date_withdrawn, date_delivered= date_delivered, qc_by = qc_by, qc_date=qc_date, additional_notes = additional_notes WHERE (case_number = case_number)", immigration);
change this line
mainly problem with these
Case_Type = Case_Type, Case_Status = Case_Status, in update query
DropDownList ct = (DropDownList)row.FindControl("case_type");
DropDownList cs = (DropDownList)row.FindControl("case_status")
;
send ct.SelectedIndex.value if want to send ids if you have bind with its value
if you want send selected index
then
send
dt.SelectedText
like
Case_Type = ct.SelectedItem.Text, Case_Status = cs.SelectedItem.Text
check this line
DropDownList cs = (DropDownList)row.FindControl("DropDownList3")
similary give the correct id for case type
in above line you are passing the ids of dropdown, you should send either its selected value of its selected index
changes
SqlCommand cmd = new SqlCommand("UPDATE intakesheet SET case_number = #case_number, case_name = #case_name, Case_Type = Case_Type, Case_Status = Case_Status, assigned_date = assigned_date, assigned_to = assigned_to, date_withdrawn= date_withdrawn, date_delivered= date_delivered, qc_by = qc_by, qc_date=qc_date, additional_notes = additional_notes WHERE (case_number = case_number)", immigration);
cmd.parameters.add("#case_number",sqldbtype.nvarchar).value = case_number // the string variable of case number
do similar for others parameters
I also had a problem with a GridView that was not updating. Inspection of the e.Newvalues Dictionary in the GridView's RowUpdating event showed that the old values for the record were being sent to the database UPDATE query. DataKeyNames was not my problem; I had it set correctly. The WHERE clause of my SELECT query referenced a control parameter against a TextBox on my form. I had inadvertently set EnableViewState for this textbox to "False". Because of this, the GridView was rebinding itself before the UPDATE occurred. Setting EnableViewState on the TextBox to "True" fixed the problem. Here is the code to see the UPDATE parameters:
Protected Sub MyGridView_RowUpdating _
(sender As Object, e As System.Web.UI.WebControls.GridViewUpdateEventArgs) _
Handles MyGridView.RowUpdating
' Inspect the parameters being sent to the database for an ASP NET GridView UPDATE.
Dim I As Integer
I = 0
For Each MVO As System.Collections.DictionaryEntry In e.OldValues
If MVO.Value Is DBNull.Value OrElse MVO.Value Is Nothing Then
Debug.Print(I.ToString + ": " + MVO.Key + " Value: ")
Else
Debug.Print(I.ToString + ": " + MVO.Key + " Value: " + MVO.Value.ToString)
End If
I += 1
Next MVO
I = 0
For Each MVN As System.Collections.DictionaryEntry In e.NewValues
If MVN.Value Is DBNull.Value OrElse MVN.Value Is Nothing Then
Debug.Print(I.ToString + ": " + MVN.Key + " Value: ")
Else
Debug.Print(I.ToString + ": " + MVN.Key + " Value: " + MVN.Value.ToString)
End If
I += 1
Next MVN
End Sub
Hi I am new to ASP and was able to create a dropdown list which list all the items from my table (DB2_INSTANCES).
Now I need to update a second table (PROCESS) with the value selected DB2_DSN. The table does not allow Null values.
If I use "SelectedValue='<%# Bind("DB2_DSN") %>' within my asp:DropDownList after I set the
DataSourceID="SqlDataSource6" DataTextField="INSTANCE" DataValueField="INSTANCE"
I get an error:
"'DropDownList6' has a SelectedValue which is invalid because it does not exist in the list of items. Parameter name: value "
If I change to "SelectedValue='<%# Bind("INSTANCE") %>' within my asp:DropDownList after I set the
DataSourceID="SqlDataSource6" DataTextField="INSTANCE" DataValueField="INSTANCE"
I get an error:
"DataBinding: 'System.Data.DataRowView' does not contain a property with the name 'INSTANCE'."
If I remove the "SelectedValue..." I get the error:
Cannot insert the value NULL into column 'DB2_DSN', table 'xxx.dbo.PROCESS'; column does not allow nulls. UPDATE fails.
The statement has been terminated.
I also tried using the DataBind() but it also gives me an error.
The other value (FTP_IND) works fine because it is listed/hardcoded.
Why does it work for FTP_IND and not for DB2_DSN?
First:
<asp:SqlDataSource ID="SqlDataSource3" runat="server"
ConnectionString="<%$ ConnectionStrings:xxxConnectionString2 %>"
DeleteCommand="DELETE FROM PROCESS WHERE NAME = #NAME AND ENVIRONMENT = #ENVIRONMENT"
SelectCommand="SELECT * FROM [PROCESS]"
UpdateCommand="UPDATE PROCESS SET ENVIRONMENT = #ENVIRONMENT, PROCESS_STATUS = #PROCESS_STATUS, IC_VALUE = #IC_VALUE,
FTP_IND = #FTP_IND, DB2_DSN = #DB2_DSN, DB2_REGION = #DB2_REGION,
ALERT_EMAIL = #ALERT_EMAIL, NOTIFY_EMAIL = #NOTIFY_EMAIL, DEBUG_INFO = #DEBUG_INFO,
LAST_UPDATE_DATE = CURRENT_TIMESTAMP, LAST_UPDATE_USERID = #UID, LAST_UPDATE_IP = #UIP WHERE (NAME = #NAME)">
<UpdateParameters>
<asp:SessionParameter Name="UID" SessionField="User_ID" Type="String" />
<asp:SessionParameter Name="UIP" SessionField="User_IP" Type="String" />
<asp:Parameter Name="ENVIRONMENT" />
<asp:Parameter Name="PROCESS_STATUS" />
<asp:Parameter Name="IC_VALUE" />
<asp:Parameter Name="FTP_IND" />
<asp:Parameter Name="DB2_DSN" />
<asp:Parameter Name="DB2_REGION" />
<asp:Parameter Name="ALERT_EMAIL" />
<asp:Parameter Name="NOTIFY_EMAIL" />
<asp:Parameter Name="DEBUG_INFO" />
<asp:Parameter Name="NAME" />
</UpdateParameters>
</asp:SqlDataSource>
<asp:SqlDataSource ID="SqlDataSource6" runat="server"
ConnectionString="<%$ ConnectionStrings:xxxConnectionString2 %>"
SelectCommand="SELECT [INSTANCE] FROM [DB2_INSTANCES] ORDER BY [INSTANCE] ASC">
</asp:SqlDataSource>
Second:
<asp:TemplateField HeaderText="FTP" SortExpression="FTP_IND">
<EditItemTemplate>
<asp:DropDownList ID="DropDownList5" runat="server"
SelectedValue='<%# Bind("FTP_IND") %>'
ToolTip="Use this to turn off and on the FTP process" Font-Size="Small">
<asp:ListItem>N</asp:ListItem>
<asp:ListItem>Y</asp:ListItem>
</asp:DropDownList>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label11" runat="server" Text='<%# Bind("FTP_IND") %>'
ToolTip="Indicates if FTP will take place" Font-Size="Small">
</asp:Label>
</ItemTemplate>
<ItemStyle Font-Size="Small" HorizontalAlign="Center" />
</asp:TemplateField>
<asp:TemplateField HeaderText = "DB2 Instance" SortExpression="DB2_DSN">
<EditItemTemplate>
<asp:DropDownList ID="DropDownList6" runat="server"
ToolTip="Use this to choose the DB2 Instance" Font-Size="Small"
DataSourceID="SqlDataSource6"
DataTextField="INSTANCE"
DataValueField="INSTANCE">
</asp:DropDownList>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label12" runat="server" Text='<%# Bind("DB2_DSN") %>'
ToolTip="Indicates the DB2 Instance being used" Font-Size="Small">
</asp:Label>
</ItemTemplate>
<ItemStyle Font-Size="Small" HorizontalAlign="Center" />
I have a standard DataGrid that looks like this:
<asp:GridView id="MyGridView"
DataSourceID="MyDataSource1"
AutoGenerateColumns="false"
AutoGenerateEditButton="true"
DataKeyNames="Id"
Runat="Server">
<Columns>
<asp:BoundField DataField="Name" HeaderText="Name" SortExpression="Name" />
<asp:TemplateField HeaderText="State">
<ItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%# Bind("State") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:DropDownList ID="IdState1" DataSource='<%# GetCategoryNames() %>' DataTextField="State" DataValueField="State" runat="server"></asp:DropDownList>
</EditItemTemplate>
</asp:TemplateField>
When updating the grid I have an UpdateCommand that looks like this:
UpdateCommand= "UPDATE [MauriceBlackburnOffices] SET [Name] = #Name, [Address1] = #Address1, [TheStates] = #State WHERE [Id] = #Id"
However the #State field is not recognized.
Must declare the scalar variable "#State".
What should the # value be?
How can I get the DropDownList value into the update statement?
I'm going to guess that you're using a SQLDataSource object to populate the GridView. If so, you're probably haven't set the UpdateParameters (MSDN Link).
Update your SQLDataSource as follows (you'll need to modify it slightly for your code):
<asp:SqlDataSource
id="MyDataSource1"
runat="server"
ConnectionString="MyDataConnectionString"
SelectCommand="SELECT * FROM Table"
UpdateCommand="UPDATE [MauriceBlackburnOffices] SET [Name] = #Name, [Address1] = #Address1, [TheStates] = #State WHERE [Id] = #Id">
<UpdateParameters>
<asp:ControlParameter Name="Name" ControlId="NameControl" PropertyName="Text"/>
<asp:ControlParameter Name="AddressID" ControlId="AddressControl" PropertyName="SelectedValue"/>
<asp:ControlParameter Name="Name" ControlId="StateControl" PropertyName="SelectedValue"/>
<asp:ControlParameter Name="ID" ControlId="IDControl" PropertyName="SelectedValue"/>
</UpdateParameters>
</asp:SqlDataSource>
You can actually do this without the UpdateParameters
By carefully looking at the full source here http://msdn.microsoft.com/en-us/library/ms972948.aspx I found the issue.
Its real wierd.
Where I say:
[TheStates] = #State
"State" MUST be the SelectedValue value in EditItemTemplate and it must be attached by the "Bind" method.
Bind("State") creates #State.
Try this one
<asp:DropDownList ID="IdState1" runat="server" DataTextField="State" DataValueField="State" SelectedValue='<%# Bind("State") %>'></asp:DropDownList>
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();
}
}