Debug GridView Update failure c# - c#

I have read and read again the links on GridView updating. I am not new to this but I cannot make the GridView Update work. Can you have a look?
<asp:SqlDataSource ID="sds_Drivers" runat="server" ConnectionString="<%$ ConnectionStrings:ThinairConnectionString %>" SelectCommand="SELECT [User_Id], [User_Active], [User_Reference], [User_Name], [User_Login], [User_Password] FROM [Users] WHERE ([User_Acct_Number] = #User_Acct_Number) ORDER BY [User_Name]" UpdateCommand="UPDATE [Users] SET [User_Active] = #User_Active, [User_Reference] = #User_Reference, [User_Name] = #User_Name, [User_Login] = #User_Login, [User_Password] = #User_Password WHERE ([User_Id] = #User_Id)" OnUpdating="sds_Drivers_Updating">
<SelectParameters>
<asp:SessionParameter Name="User_Acct_Number" SessionField="Acct_Number" Type="String" />
</SelectParameters>
<UpdateParameters>
<asp:Parameter Name="User_Active" Type="Int32" />
<asp:Parameter Name="User_Reference" Type="String" />
<asp:Parameter Name="User_Name" Type="String" />
<asp:Parameter Name="User_Login" Type="String" />
<asp:Parameter Name="User_Password" Type="String" />
<asp:Parameter Name="User_Id" Type="Int32" />
</UpdateParameters>
</asp:SqlDataSource>
</p>
<p>
<asp:GridView ID="gv_Drivers" runat="server"
Width="100%"
AllowSorting="True"
AutoGenerateColumns="False"
DataKeyNames="User_Id"
ConvertEmptyStringToNull="False"
DataSourceID="sds_Drivers"
CellSpacing="2"
CellPadding="2"
HeaderStyle-ForeColor="Black"
HeaderStyle-Wrap="true">
<Columns>
<asp:CommandField EditText="Edit" ShowEditButton="True" ValidationGroup="Group3" />
<asp:BoundField DataField="User_Id" HeaderText="User Id" ReadOnly="true" SortExpression="User_Id" />
<asp:BoundField DataField="User_Active" HeaderText="1 = Active / 0 = Inactive" SortExpression="User_Active" />
<asp:BoundField DataField="User_Reference" HeaderText="Your Reference" SortExpression="User_Reference" />
<asp:BoundField DataField="User_Name" HeaderText="User Name" SortExpression="User_Name" />
<asp:BoundField DataField="User_Login" HeaderText="User Login" SortExpression="User_Login" />
<asp:BoundField DataField="User_Password" HeaderText="User Password" SortExpression="User_Password" />
</Columns>
<EmptyDataTemplate>
No Drivers Loaded
</EmptyDataTemplate>
</asp:GridView>
What I tried for debugging in code behind:
protected void sds_Drivers_Updating(object sender, SqlDataSourceCommandEventArgs e)
{
foreach (SqlParameter p in e.Command.Parameters)
{
Response.Write(p.ParameterName + ": " + p.Value + "<br />");
}
}
The good news is I have values. The bad news is that these are not the new values in the edit fields.
What did I miss?
Thanks in Advance!

You can try this:
protected void sds_Drivers_Updating(object sender, SqlDataSourceCommandEventArgs e)
{
foreach (SqlParameter p in e.Command.Parameters)
{
Response.Write(p.ParameterName + ": " + p.NewValues + "<br />");
}
}

Related

System.Data.DataRowView' does not contain a property with the name 'State'

<asp:GridView ID="dgvCustomers" runat="server" AutoGenerateColumns="False" HorizontalAlign="Center" DataKeyNames="ID" DataSourceID="dsCustomerTickets" BackColor="White" BorderColor="#DEDFDE" BorderStyle="None" BorderWidth="1px" CellPadding="4" ForeColor="Black" GridLines="Vertical" OnRowUpdated="dgvCustomers_RowUpdated">
<AlternatingRowStyle BackColor="White" />
<Columns>
<asp:CommandField EditImageUrl="~/svg/edit.png" UpdateImageUrl="~/svg/save.png" CancelImageUrl="~/svg/cancel.png" ButtonType="Image" ShowEditButton="True" />
<asp:BoundField DataField="ID" HeaderText="ID" InsertVisible="False" ReadOnly="True" SortExpression="ID" />
<asp:BoundField DataField="Title" HeaderText="Title" SortExpression="Title" />
<asp:BoundField DataField="Description" HeaderText="Description" SortExpression="Description" />
<asp:BoundField DataField="System" HeaderText="System" SortExpression="System" />
<asp:BoundField DataField="LoggedDate" HeaderText="LoggedDate" SortExpression="LoggedDate" />
<asp:BoundField DataField="ClosedDate" HeaderText="ClosedDate" SortExpression="ClosedDate" />
<asp:BoundField DataField="Resolution" HeaderText="Resolution" SortExpression="Resolution" />
<%--<asp:BoundField DataField="HistoryID" HeaderText="HistoryID" SortExpression="HistoryID" />--%>
<%--<asp:BoundField DataField="Priority" HeaderText="Priority" SortExpression="Priority" />--%>
<asp:BoundField DataField="LoggedBy" HeaderText="LoggedBy" SortExpression="LoggedBy" />
<asp:TemplateField HeaderText="State" SortExpression="State2">
<EditItemTemplate>
<asp:DropDownList ID="ddlstate" runat="server" DataSourceID="SqlDataSource2" DataTextField="State" DataValueField="ID" SelectedValue='<%# Bind("State") %>' AppendDataBoundItems="true">
<asp:ListItem Text="Select a State" Value="" />
</asp:DropDownList>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%# Bind("State2") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Priority" SortExpression="State3">
<EditItemTemplate>
<asp:DropDownList ID="ddlpriority" runat="server" DataSourceID="SqlDataSource3" DataTextField="Priority" DataValueField="ID" SelectedValue='<%# Bind("Priority") %>' AppendDataBoundItems="true">
<asp:ListItem Text="Select Priority" Value="" />
</asp:DropDownList>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label2" runat="server" Text='<%# Bind("State3") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
<FooterStyle BackColor="#CCCC99" />
<HeaderStyle BackColor="#6B696B" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="#F7F7DE" ForeColor="Black" HorizontalAlign="Right" />
<RowStyle BackColor="#F7F7DE" />
<SelectedRowStyle BackColor="#0099ff" Font-Bold="True" ForeColor="White" />
<SortedAscendingCellStyle BackColor="#FBFBF2" />
<SortedAscendingHeaderStyle BackColor="#848384" />
<SortedDescendingCellStyle BackColor="#EAEAD3" />
<SortedDescendingHeaderStyle BackColor="#575357" />
</asp:GridView>
<asp:SqlDataSource ID="dsCustomerTickets" runat="server" ConnectionString="<%$ ConnectionStrings:TicketsSupportConnectionString %>" DeleteCommand="DELETE FROM [Tickets] WHERE [ID] = #ID" InsertCommand="INSERT INTO [Tickets] ([Title], [Description], [System], [LoggedDate], [ClosedDate], [Resolution], [Priority], [HistoryID], [LoggedBy], [State]) VALUES (#Title, #Description, #System, #LoggedDate, #ClosedDate, #Resolution, #Priority, #HistoryID, #LoggedBy, #State)" SelectCommand="SELECT T.ID, T.Title, T.Description, T.System, T.Attachments, T.LoggedDate, T.ClosedDate, T.Resolution, T.Priority, T.LoggedBy, S.State AS State2, p.Priority AS State3 FROM Tickets AS T INNER JOIN State AS S ON T.State = S.ID INNER JOIN Priority AS p ON T.Priority = p.ID WHERE (T.LoggedBy = #LoggedBy)" UpdateCommand="UPDATE Tickets SET Description = #Description, System = #System, ClosedDate = #ClosedDate, Resolution = #Resolution, Priority = #Priority, HistoryID = #HistoryID, State = #State WHERE (ID = #ID)">
<DeleteParameters>
<asp:Parameter Name="ID" Type="Int32" />
</DeleteParameters>
<InsertParameters>
<asp:Parameter Name="Title" Type="String" />
<asp:Parameter Name="Description" Type="String" />
<asp:Parameter Name="System" Type="String" />
<asp:Parameter Name="LoggedDate" Type="DateTime" />
<asp:Parameter Name="ClosedDate" Type="DateTime" />
<asp:Parameter Name="Resolution" Type="String" />
<asp:Parameter Name="Priority" Type="Int32" />
<asp:Parameter Name="HistoryID" Type="Int32" />
<asp:Parameter Name="LoggedBy" Type="String" />
<asp:Parameter Name="State" Type="Int32" />
</InsertParameters>
<SelectParameters>
<asp:QueryStringParameter Name="LoggedBy" QueryStringField="u" />
</SelectParameters>
<UpdateParameters>
<asp:Parameter Name="Description" Type="String" />
<asp:Parameter Name="System" Type="String" />
<asp:Parameter Name="ClosedDate" Type="DateTime" />
<asp:Parameter Name="Resolution" Type="String" />
<asp:Parameter Name="Priority" Type="Int32" />
<asp:Parameter Name="HistoryID" Type="Int32" />
<asp:Parameter Name="State" Type="Int32" />
<asp:Parameter Name="ID" Type="Int32" />
</UpdateParameters>
</asp:SqlDataSource>
<asp:SqlDataSource ID="SqlDataSource2" runat="server" ConnectionString="<%$ ConnectionStrings:TicketsSupportConnectionString %>" SelectCommand="SELECT [ID],[State] FROM [dbo].[State]"></asp:SqlDataSource>
With the above code I get the error constantly.
In SQL if I run the SqlDataSource2 query I get results (ID and State).
I tried Changing my queries and editing my dragged SqlDataSource2 in the query builder.
As soon as I click on the commandfield "EditImageUrl" I get the above error.
Maybe I am looking at my code to long to notice any issues.
I have googled it with no luck looking at stuff like:
I have looked at Here
And the same here, I have bind instead of Eval in the dropdown list.
I also tried changing my sqldatasource to:
Select * from State
Select ID, State from State
Select ID, State from dbo.State
Any help will be appreciated.
Edit and Update
In EditTemplate you fill in aspDropDown from SqlDataSource2 with correct DataTextField="State" DataValueField="ID". But SelectedValue belongs to <asp:SqlDataSource ID="dsCustomerTickets". So you need T.State in SelectCommand to make binding SelectedValue='<%# Bind("State") %>' correct. Also there is no need in Bind in ItemTemplate. Eval("State2") is enough.
And 1st SqlDataSource should be
<asp:SqlDataSource ID="dsCustomerTickets" runat="server"
ConnectionString="<%$ ConnectionStrings:TicketsSupportConnectionString %>"
DeleteCommand="DELETE FROM [Tickets] WHERE [ID] = #ID"
InsertCommand="INSERT INTO [Tickets] (/*removed for shortness*/ [State]) VALUES ( #State2)"
SelectCommand="SELECT /*your list*/ T.State, S.State AS State2, p.Priority AS State3 FROM Tickets AS T INNER JOIN State AS S ON T.State = S.ID INNER JOIN Priority AS p ON T.Priority = p.ID WHERE (T.LoggedBy = #LoggedBy)"
UpdateCommand="UPDATE Tickets SET /*removed for shortness*/ State = #State2 WHERE (ID = #ID)">
<DeleteParameters>
<asp:Parameter Name="ID" Type="Int32" />
</DeleteParameters>
<InsertParameters>
<%--your parameters removed for shortness--%>
<asp:Parameter Name="State" Type="Int32" />
</InsertParameters>
<SelectParameters>
<asp:QueryStringParameter Name="LoggedBy" QueryStringField="u" />
</SelectParameters>
<UpdateParameters>
<%--your parameters removed for shortness--%>
<asp:Parameter Name="State" Type="Int32" />
<asp:Parameter Name="ID" Type="Int32" />
</UpdateParameters>
</asp:SqlDataSource>

Looping through ListBox to add multiple selected values to a single database field

I am trying to add the multiple selected values from the ListBox into the Database. Multiple test names are to be selected for each patient (depending upon the requirements) and they are to be inserted into the column named TestName.
For example: If I select ANA, CBC for a patient, it should add BOTH values in the TESTNAME column against that patient name.
I have tried a few things suggested on the internet, but I have been unsuccessful. I am posting my related ASP.NET code along with C# code (my latest try).
With the latest try, it throws an error saying:
The variable name '#TestName' has already been declared. Variable names must be unique within a query batch or stored procedure.
ASP.NET code for the gridview:
<div id="mbody">
<div class="gview">
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" CssClass="gview" DataSourceID="SqlDataSource1" DataKeyNames="PID">
<Columns>
<asp:CommandField ShowDeleteButton="True" />
<asp:BoundField DataField="PID" HeaderText="PID" InsertVisible="False" ReadOnly="True" SortExpression="PID" />
<asp:BoundField DataField="Pname" HeaderText="Pname" SortExpression="Pname" />
<asp:BoundField DataField="Gender" HeaderText="Gender" SortExpression="Gender" />
<asp:BoundField DataField="Consultant" HeaderText="Consultant" SortExpression="Consultant" />
<asp:BoundField DataField="TestName" HeaderText="TestName" SortExpression="TestName" />
<asp:BoundField DataField="RequestDate" HeaderText="RequestDate" SortExpression="RequestDate" />
<asp:BoundField DataField="ReportDate" HeaderText="ReportDate" SortExpression="ReportDate" />
</Columns>
</asp:GridView>
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:SMCConnectionString %>" SelectCommand="SELECT [PID], [Pname], [Gender], [Consultant], [TestName], [RequestDate], [ReportDate] FROM [Patient]" DeleteCommand="DELETE FROM [Patient] WHERE [PID] = #PID" InsertCommand="INSERT INTO [Patient] ([Pname], [Gender], [Consultant], [TestName], [RequestDate], [ReportDate]) VALUES (#Pname, #Gender, #Consultant, #TestName, #RequestDate, #ReportDate)" UpdateCommand="UPDATE [Patient] SET [Pname] = #Pname, [Gender] = #Gender, [Consultant] = #Consultant, [TestName] = #TestName, [RequestDate] = #RequestDate, [ReportDate] = #ReportDate WHERE [PID] = #PID">
<DeleteParameters>
<asp:Parameter Name="PID" Type="Int32" />
</DeleteParameters>
<InsertParameters>
<asp:Parameter Name="Pname" Type="String" />
<asp:Parameter Name="Gender" Type="String" />
<asp:Parameter Name="Consultant" Type="String" />
<asp:Parameter Name="TestName" Type="String" />
<asp:Parameter Name="RequestDate" Type="String" />
<asp:Parameter Name="ReportDate" Type="String" />
</InsertParameters>
<UpdateParameters>
<asp:Parameter Name="Pname" Type="String" />
<asp:Parameter Name="Gender" Type="String" />
<asp:Parameter Name="Consultant" Type="String" />
<asp:Parameter Name="TestName" Type="String" />
<asp:Parameter Name="RequestDate" Type="String" />
<asp:Parameter Name="ReportDate" Type="String" />
<asp:Parameter Name="PID" Type="Int32" />
</UpdateParameters>
</asp:SqlDataSource>
</div>
</div>
ListBox.aspx:
<asp:ListBox ID="ListBox1" runat="server" SelectionMode="Multiple" Height="57px" Width="270px">
<asp:ListItem>ANA</asp:ListItem>
<asp:ListItem>ASMA</asp:ListItem>
<asp:ListItem>ASO-titres</asp:ListItem>
<asp:ListItem>ESR</asp:ListItem>
<asp:ListItem>CBC</asp:ListItem>
<asp:ListItem>Anti-double Stranded DNA ab</asp:ListItem>
</asp:ListBox>
ListBox.aspx.cs:
protected void Button3_Click(object sender, EventArgs e)
{
string str = "update Patient set TestName=#TestName, RequestDate=#RequestDate ,ReportDate=#ReportDate, Consultant=#Consultant where PID = '" + TextBox7.Text + "'";
cmd = new SqlCommand(str, con);
foreach (ListItem li in ListBox1.Items)
{
if (li.Selected)
{
cmd.Parameters.AddWithValue("#TestName", ListBox1.SelectedItem.Text);
}
}
cmd.Parameters.AddWithValue("#RequestDate", TextBox4.Text.ToString());
cmd.Parameters.AddWithValue("#ReportDate", TextBox5.Text.ToString());
cmd.Parameters.AddWithValue("#Consultant", TextBox6.Text);
con.Open();
int flag = cmd.ExecuteNonQuery();
if (flag == 1) //On successful updation, shows a popup message
{
string msg = "Operation Successful";
System.Text.StringBuilder sb = new System.Text.StringBuilder();
sb.Append("<script type = 'text/javascript'>");
sb.Append("window.onload=function(){");
sb.Append("alert('");
sb.Append(msg);
sb.Append("')};");
sb.Append("</script>");
ClientScript.RegisterClientScriptBlock(this.GetType(), "alert", sb.ToString());
}
else if (flag == 0)
{
string msg1 = "Operation Unsuccessful";
System.Text.StringBuilder sb1 = new System.Text.StringBuilder();
sb1.Append("<script type = 'text/javascript'>");
sb1.Append("window.onload=function(){");
sb1.Append("alert('");
sb1.Append(msg1);
sb1.Append("')};");
sb1.Append("</script>");
ClientScript.RegisterClientScriptBlock(this.GetType(), "alert", sb1.ToString());
}
con.Close();
}
Maybe I need to append or concatenate or something, but I am not sure how to do that.
You cannot add the same parameter name twice. You mentioned:
should add BOTH values in the TESTNAME column
so I suppose you want to concatenate the selected values, if so then you can do something like:
var items = new List<string>();
foreach (ListItem li in ListBox1.Items)
{
if (li.Selected)
{
items.Add(li.Text);
}
}
cmd.Parameters.AddWithValue("#TestName", string.Join(",", items));

edit in detailsview with dropdownlist

I am fairly new at ASP.NET c#. I would like to edit a detailsview with a dropdown list. I have followed the instructions on this link -- This link-- and it was exactly what I orrigionally thought of. This is flawed however, because although I can see the items on my dropdown list, it does not actually update the database. I am at a loss. I have been trying to find an answer for a couple of days now and am unsure of what I need to do. Is there something I need to do in the backend? I will attach my code at the end as well. Currently I have nothing going on in the backend.
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:it_supportConnectionString %>" DeleteCommand="DELETE FROM [issues] WHERE [issue_id] = #issue_id" InsertCommand="INSERT INTO [issues] ([requestor], [email], [urgency], [issue_type], [details], [priority], [issue_manager], [status], [date_reported]) VALUES (#requestor, #email, #urgency, #issue_type, #details, #priority, #issue_manager, #status, #date_reported)" SelectCommand="SELECT issues.issue_id, issues.requestor, issues.email, issues.phone, issues.urgency, issues.issue_type_id,Issue_Type.[Issue_Type_ID], Issue_Type.[Issue_Type], issues.details, issues.priority, issues.issue_manager, issues.status, issues.date_reported, issues.notes FROM issues LEFT OUTER JOIN Issue_Type ON Issue_Type.Issue_Type_Id = issues.issue_type_id WHERE (issues.issue_id = #issue_id)" UpdateCommand="UPDATE issues SET requestor = #requestor, email = #email, urgency = #urgency, details = #details, priority = #priority, issue_manager = #issue_manager, status = #status, date_reported = #date_reported WHERE (issue_id = #issue_id)">
<DeleteParameters>
<asp:Parameter Name="issue_id" Type="Int32" />
</DeleteParameters>
<InsertParameters>
<asp:Parameter Name="requestor" Type="String" />
<asp:Parameter Name="email" Type="String" />
<asp:Parameter Name="urgency" Type="String" />
<asp:Parameter Name="issue_type" Type="String" />
<asp:Parameter Name="details" Type="String" />
<asp:Parameter Name="priority" Type="Int32" />
<asp:Parameter Name="issue_manager" Type="String" />
<asp:Parameter Name="status" Type="String" />
<asp:Parameter Name="date_reported" Type="DateTime" />
</InsertParameters>
<SelectParameters>
<asp:QueryStringParameter Name="issue_id" QueryStringField="id" Type="Int32" />
</SelectParameters>
<UpdateParameters>
<asp:Parameter Name="requestor" Type="String" />
<asp:Parameter Name="email" Type="String" />
<asp:Parameter Name="urgency" Type="String" />
<asp:Parameter Name="details" Type="String" />
<asp:Parameter Name="priority" Type="Int32" />
<asp:Parameter Name="issue_manager" Type="String" />
<asp:Parameter Name="status" Type="String" />
<asp:Parameter Name="date_reported" Type="DateTime" />
<asp:Parameter Name="issue_id" Type="Int32" />
</UpdateParameters>
</asp:SqlDataSource>
<asp:SqlDataSource ID="SqlDataSource2" runat="server" ConnectionString="<%$ ConnectionStrings:it_supportConnectionString %>" SelectCommand="SELECT Issue_Type.Issue_Type_Id, Issue_Type.Issue_Type, issues.issue_type_id AS Expr1 FROM Issue_Type LEFT OUTER JOIN issues ON Issue_Type.Issue_Type_Id = issues.issue_type_id"></asp:SqlDataSource>
<asp:DetailsView ID="DetailsView1" runat="server" AutoGenerateRows="False" BackColor="#DEBA84" BorderColor="#DEBA84" BorderStyle="None" BorderWidth="1px" CellPadding="3" CellSpacing="2" DataSourceID="SqlDataSource1" Height="50px" Width="125px">
<EditRowStyle BackColor="#738A9C" Font-Bold="True" ForeColor="White" />
<Fields>
<asp:BoundField DataField="issue_id" HeaderText="issue_id" InsertVisible="False" ReadOnly="True" SortExpression="issue_id" />
<asp:BoundField DataField="requestor" HeaderText="requestor" SortExpression="requestor" />
<asp:BoundField DataField="email" HeaderText="email" SortExpression="email" />
<asp:BoundField DataField="phone" HeaderText="phone" SortExpression="phone" />
<asp:BoundField DataField="urgency" HeaderText="urgency" SortExpression="urgency" />
<asp:TemplateField HeaderText="issue_type_id" SortExpression="issue_type_id">
<EditItemTemplate>
<asp:DropDownList ID="DropDownList1" runat="server" DataSourceID="SqlDataSource2" DataTextField="Issue_Type_Id" DataValueField="Expr1" SelectedValue='<%# Bind("issue_type_id") %>'>
</asp:DropDownList>
</EditItemTemplate>
<InsertItemTemplate>
<asp:TextBox ID="TextBox1" runat="server" Text='<%# Bind("issue_type_id") %>'></asp:TextBox>
</InsertItemTemplate>
<ItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%# Bind("issue_type_id") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="Issue_Type" HeaderText="Issue_Type" SortExpression="Issue_Type" />
<asp:BoundField DataField="details" HeaderText="details" SortExpression="details" />
<asp:BoundField DataField="priority" HeaderText="priority" SortExpression="priority" />
<asp:BoundField DataField="issue_manager" HeaderText="issue_manager" SortExpression="issue_manager" />
<asp:BoundField DataField="status" HeaderText="status" SortExpression="status" />
<asp:BoundField DataField="date_reported" HeaderText="date_reported" SortExpression="date_reported" />
<asp:BoundField DataField="notes" HeaderText="notes" SortExpression="notes" />
<asp:CommandField ShowDeleteButton="True" ShowEditButton="True" />
</Fields>
<FooterStyle BackColor="#F7DFB5" ForeColor="#8C4510" />
<HeaderStyle BackColor="#A55129" Font-Bold="True" ForeColor="White" />
<PagerStyle ForeColor="#8C4510" HorizontalAlign="Center" />
<RowStyle BackColor="#FFF7E7" ForeColor="#8C4510" />
</asp:DetailsView>

changing DetailsViewMode on Page_Load event

I have a simple DetailsView control connected to a data source consisting of two T-SQL queries (which work fine). However, when I try to change the mode (depending on the id in the URL) to "Edit" on Page_Load event nothing shows while "Insert" works fine. Everything seems properly data-bound.
Also, how do I access the BoundField value (the text itself) from code-behind (FindControl always returns null for some reason)? I want to have a default value there when the page loads.
Markup:
<body>
<form id="form1" runat="server">
<div class="register" runat="server">
<asp:DetailsView ID="DV" runat="server" HorizontalAlign="Center"
Height="100px" Width="170px"
AutoGenerateRows="False" DataSourceID="RegisterUser"
OnItemCommand="Button_click"
OnItemInserted="Insert_click" OnItemUpdated="Edit_click">
<Fields>
<asp:BoundField DataField="username" HeaderText="Name"
SortExpression="username" />
<asp:TemplateField HeaderText="Password">
<EditItemTemplate>
<asp:TextBox ID="Password" runat="server" TextMode="Password" Text='<%# Bind("userPassword") %>'></asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="userEmail" HeaderText="Email"
SortExpression="userEmail" />
<asp:CommandField ShowInsertButton="True" ShowEditButton="True" />
</Fields>
</asp:DetailsView>
<asp:SqlDataSource ID="RegisterUser" runat="server"
ConnectionString="<%$ ConnectionStrings:usersConnectionString %>"
InsertCommand="INSERT INTO korisnik(username, userPassword, userEmail) VALUES (#username, #userPassword, #userEmail)"
UpdateCommand="UPDATE korisnik SET userPassword = #userPassword, userEmail = #userEmail WHERE (username = #username)">
<InsertParameters>
<asp:Parameter Name="username" Type="String" />
<asp:Parameter Name="userPassword" Type="String" />
<asp:Parameter Name="userEmail" Type="String" />
</InsertParameters>
<UpdateParameters>
<asp:Parameter Name="userPassword" Type="String" />
<asp:Parameter Name="userEmail" Type="String" />
<asp:Parameter Name="username" Type="String" />
</UpdateParameters>
</asp:SqlDataSource>
<asp:Label ID="Message_label" ForeColor="red" Visible="false" runat="server" Text="[messageLabel]"></asp:Label>
</div>
</form>
</body>
Code-behind:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
string id = Request.QueryString["id"];
// EDIT mode
if (id == "Change_data_button")
{
DV.DefaultMode = DetailsViewMode.Edit;
//DV.DataSource = RegisterUser;
//DV.DataBind();
DV.Fields[0].Visible = false; // preventing the value from being changed (one cannot change a username)
/* found this snippet somewhere but FindControl returns null */
TextBox user;
user = (TextBox)DV.FindControl("username");
user.Text = Session["LoggedUser"].ToString();
}
// INSERT mode
else if (id == "Register_button")
{
DV.DefaultMode = DetailsViewMode.Insert;
}
}
}
First, I don't see any setting for SelectCommand in SqlDataSource control named RegisterUser, I don't think that you will have data in DetailsView to edit in EditMode.
So you have to set SelectCommand (also SelectParameters if have them) such as the following sample
<asp:SqlDataSource ID="RegisterUser" runat="server"
ConnectionString="<%$ ConnectionStrings:usersConnectionString %>"
SelectCommand="SELECT * FROM korisnik WHERE username = #username"
InsertCommand="INSERT INTO korisnik(username, userPassword, userEmail) VALUES (#username, #userPassword, #userEmail)"
UpdateCommand="UPDATE korisnik SET userPassword = #userPassword, userEmail = #userEmail WHERE (username = #username)">
<SelectParameters>
<asp:Parameter Name="username" Type="String" />
</SelectParameters>
<InsertParameters>
<asp:Parameter Name="username" Type="String" />
<asp:Parameter Name="userPassword" Type="String" />
<asp:Parameter Name="userEmail" Type="String" />
</InsertParameters>
<UpdateParameters>
<asp:Parameter Name="userPassword" Type="String" />
<asp:Parameter Name="userEmail" Type="String" />
<asp:Parameter Name="username" Type="String" />
</UpdateParameters>
</asp:SqlDataSource>
Secound, in Page_Load handler, this line user = (TextBox)DV.FindControl("username"); should always be null, because you don't have a control names "username", you have only DataField named "username".
If you want to hide username field in edit mode, you have to set username field as Key of DetailView (DataKeyNames setting). But I suggest that you could set username to be read-only instead of hiding it (set ReadOnly="true" in BoundField). Final, try to get their values in ItemUpdating event handler (OnItemUpdating setting)
Here is the sample as my suggestion:
<asp:DetailsView ID="DV" runat="server" HorizontalAlign="Center"
Height="100px" Width="170px"
AutoGenerateRows="False" DataSourceID="RegisterUser"
OnItemCommand="Button_click"
OnItemInserted="Insert_click" OnItemUpdated="Edit_click"
OnItemUpdating="DV_ItemUpdating"
DataKeyNames="username">
<Fields>
<asp:BoundField DataField="username" HeaderText="Name"
SortExpression="username"
ReadOnly="true"/>
<asp:TemplateField HeaderText="Password">
<EditItemTemplate>
<asp:TextBox ID="Password" runat="server" TextMode="Password" Text='<%# Bind("userPassword") %>'></asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="userEmail" HeaderText="Email"
SortExpression="userEmail" />
<asp:CommandField ShowInsertButton="True" ShowEditButton="True" />
</Fields>
</asp:DetailsView>
Code-behide:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
string id = Request.QueryString["id"];
// EDIT mode
if (id == "Change_data_button")
{
DV.DefaultMode = DetailsViewMode.Edit;
}
// INSERT mode
else if (id == "Register_button")
{
DV.DefaultMode = DetailsViewMode.Insert;
}
}
}
protected void DV_ItemUpdating(object sender, DetailsViewUpdateEventArgs e)
{
string username = e.Keys["username"].ToString();
TextBox txtPassword = (TextBox)DV.FindControl("Password");
string password = txtPassword.Text;
string email = e.NewValues["userEmail"].ToString();
RegisterUser.UpdateParameters["userPassword"].DefaultValue = password;
RegisterUser.UpdateParameters["userEmail"].DefaultValue = email;
RegisterUser.UpdateParameters["username"].DefaultValue = username;
RegisterUser.Update();
}
You should use: DetailsView.ChangeMode() method to programmatically switch the DetailsView control between edit, insert, and read-only mode.
if (id == "Change_data_button")
{
DV.ChangeMode(DetailsViewMode.Edit);
//DV.DataSource = RegisterUser;
//DV.DataBind();
...
...
}
Also, access the Bound Fields value as::
string _userName = DV.Rows[0].Cells[0].Text.ToString();

Casting object to CheckBox in bulk updates

I was following this so far everything is fine with a textbox but when try to modify it to checkbox it gives an error: Unable to cast object of type 'System.Web.UI.WebControls.TextBox' to type 'System.Web.UI.WebControls.CheckBox'.
Its working when I use TextBox but how can I make all the CheckBox editable in bulk updates?
Here's the sample code behind
private bool tableCopied = false;
private DataTable originalDataTable;
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
if (!tableCopied)
{
originalDataTable = ((DataRowView)e.Row.DataItem).Row.Table.Copy();
ViewState["originalValueTable"] = originalDataTable;
tableCopied = true;
}
}
protected void UpdateButton_Click(object sender, EventArgs e)
{
originalDataTable = (DataTable)ViewState["originalValueTable"];
foreach (GridViewRow r in GridView1.Rows)
if (IsRowModified(r))
{
GridView1.UpdateRow(r.RowIndex, false);
}
tableCopied = false;
GridView1.DataBind();
}
protected bool IsRowModified(GridViewRow r)
{
int currentID;
string currentreservedate;
string currentisapproved;
currentID = Convert.ToInt32(GridView1.DataKeys[0].Value);
currentreservedate = ((TextBox)r.FindControl("reservedateTextBox")).Text;
currentisapproved = ((CheckBox)r.FindControl("isapprovedCheckBox")).Text;
DataRow row = originalDataTable.Select(String.Format("reservationid = {0}", currentID))[0];
if (!currentreservedate.Equals(row["reservedate"].ToString()))
if (!currentisapproved.Equals(row["isapproved"].ToString()))
{
return true;
}
return false;
}
}
}
Here's the aspx markup
Pending Reservation<br />
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:LibrarySystemConnectionString %>"
SelectCommand="SELECT dbo.BookReservation.reservationid, dbo.BookReservation.bookid, dbo.BookReservation.EmployeeID, dbo.BookReservation.reservedate, dbo.BookReservation.isapproved, dbo.BookReservation.reschedule, dbo.BookReservation.isdeleted, dbo.TblBooks.booktitle FROM dbo.BookReservation INNER JOIN dbo.TblBooks ON dbo.BookReservation.bookid = dbo.TblBooks.bookid"
DeleteCommand="DELETE FROM [BookReservation] WHERE [reservationid] = #reservationid"
InsertCommand="INSERT INTO [BookReservation] ([bookid], [EmployeeID], [reservedate], [isapproved], [reschedule], [isdeleted]) VALUES (#bookid, #EmployeeID, #reservedate, #isapproved, #reschedule, #isdeleted)"
UpdateCommand="UPDATE [BookReservation] SET [bookid] = #bookid, [EmployeeID] = #EmployeeID, [reservedate] = #reservedate, [isapproved] = #isapproved, [reschedule] = #reschedule, [isdeleted] = #isdeleted WHERE [reservationid] = #reservationid">
<DeleteParameters>
<asp:Parameter Name="reservationid" Type="Int32" />
</DeleteParameters>
<UpdateParameters>
<asp:Parameter Name="bookid" Type="Int64" />
<asp:Parameter Name="EmployeeID" Type="String" />
<asp:Parameter Name="reservedate" Type="DateTime" />
<asp:Parameter Name="isapproved" Type="Boolean" />
<asp:Parameter Name="reschedule" Type="Boolean" />
<asp:Parameter Name="isdeleted" Type="Boolean" />
<asp:Parameter Name="reservationid" Type="Int32" />
</UpdateParameters>
<InsertParameters>
<asp:Parameter Name="bookid" Type="Int64" />
<asp:Parameter Name="EmployeeID" Type="String" />
<asp:Parameter Name="reservedate" Type="DateTime" />
<asp:Parameter Name="isapproved" Type="Boolean" />
<asp:Parameter Name="reschedule" Type="Boolean" />
<asp:Parameter Name="isdeleted" Type="Boolean" />
</InsertParameters>
</asp:SqlDataSource>
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" AllowPaging="true" AllowSorting="true"
DataKeyNames="reservationid, bookid, EmployeeID, reservedate " DataSourceID="SqlDataSource1" OnRowDataBound="GridView1_RowDataBound" >
<Columns>
<asp:BoundField DataField="reservationid" HeaderText="reservationid"
InsertVisible="False" ReadOnly="True"
SortExpression="reservationid" Visible="False" />
<asp:BoundField DataField="bookid" HeaderText="bookid"
SortExpression="bookid" Visible="False" />
<asp:BoundField DataField="booktitle" HeaderText="Title"
SortExpression="booktitle" />
<asp:BoundField DataField="EmployeeID" HeaderText="Reserved by"
SortExpression="EmployeeID" />
<%--<asp:BoundField DataField="reservedate" HeaderText="Date reserved"
SortExpression="reservedate" />--%>
<asp:TemplateField HeaderText="Reserve Date"
SortExpression="reservedate">
<EditItemTemplate>
<asp:TextBox ID="reservedateTextBox" runat="server" Text='<%# Bind("reservedate") %>'>
</asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:TextBox ID="reservedateTextBox" runat="server" Text='<%# Bind("reservedate") %>'>
</asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<%--<asp:CheckBoxField DataField="isapproved" HeaderText="Approved"
SortExpression="isapproved" />--%>
<asp:TemplateField HeaderText="Apprvoed"
SortExpression="isapproved">
<EditItemTemplate>
<asp:TextBox ID="isapprovedCheckBox" runat="server" Text='<%# Bind("isapproved") %>'>
</asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:TextBox ID="isapprovedCheckBox" runat="server" Text='<%# Bind("isapproved") %>'>
</asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:CheckBoxField DataField="reschedule" HeaderText="Reschedule"
SortExpression="reschedule" />
<asp:CheckBoxField DataField="isdeleted" HeaderText="Deleted"
SortExpression="isdeleted" />
</Columns>
</asp:GridView>
<br />
<br />
<asp:Button ID="UpdateButton" runat="server" Text="Update" OnClick="UpdateButton_Click" />
<br />
Help would be much appreciated! Thanks in advance!
I think that to answer this question, the contents of the aspx file are required, but I'll try to help. More than likely the element in your form, isapprovedCheckBox, is still set to the the tag asp:Text. As a result the system can't convert the textbox to a checkbox.
Could you include your aspx content as well?

Categories

Resources