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();
Related
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 />");
}
}
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));
I am new to ASP.net so I'm just now getting into using TemplateFields. I have a DetailsView which contains a DropDownList that has it's items populated from my codebehind when the DetailsView is in EditMode.
This much is working fine. However, after selecting an item from my DropDownList, and clicking "Update" the selection is not updated, however the other DetailsView form values are.
Here is my code:
DetailsView & SQL Queries:
<asp:DetailsView ID="DetailsView1" runat="server" Height="50px" Width="315px"
AutoGenerateRows="False" DataKeyNames="ID" DataSourceID="SqlDataSource1"
OnDataBound="DetailsView1_DataBound">
<Fields>
<asp:CommandField ShowEditButton="True" ControlStyle-CssClass="button" >
<ControlStyle CssClass="button"></ControlStyle>
</asp:CommandField>
<asp:BoundField DataField="FirstName" HeaderText="First Name"
SortExpression="FirstName" />
<asp:BoundField DataField="LastName" HeaderText="Last Name"
SortExpression="LastName" />
<asp:BoundField DataField="Email" HeaderText="Email" SortExpression="Email" />
<asp:BoundField DataField="JobID" HeaderText="JobID" SortExpression="JobID" />
<asp:BoundField DataField="SupervisorID" HeaderText="Supervisor"
SortExpression="SupervisorID" />
<asp:TemplateField HeaderText="Hire Date" SortExpression="HireDate">
<EditItemTemplate>
<span class="input-type-text margin-right relative"><asp:TextBox ID="TextBox1" runat="server" Text='<%# Bind("HireDate","{0:d}") %>' CssClass="datepicker"></asp:TextBox><img src="images/icons/fugue/calendar-month.png" width="16" height="16"></span>
</EditItemTemplate>
<InsertItemTemplate>
<asp:TextBox ID="TextBox1" runat="server" Text='<%# Bind("HireDate","{0:d}") %>'></asp:TextBox>
</InsertItemTemplate>
<ItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%# Bind("HireDate","{0:d}") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Status" SortExpression="Status">
<EditItemTemplate>
<asp:DropDownList ID="StatusList" runat="server">
</asp:DropDownList>
</EditItemTemplate>
<InsertItemTemplate>
<asp:TextBox ID="TextBox2" runat="server" Text='<%# Bind("Status") %>'></asp:TextBox>
</InsertItemTemplate>
<ItemTemplate>
<asp:Label ID="Label2" runat="server" Text='<%# Bind("Status") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Fields>
</asp:DetailsView>
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:dbConnectionString %>"
DeleteCommand="DELETE FROM [Users] WHERE [ID] = #ID"
InsertCommand="INSERT INTO [Users] ([ClientID], [UserName], [Password], [FirstName], [LastName], [Email], [JobID], [SupervisorID], [HireDate], [Status]) VALUES (#ClientID, #UserName, #Password, #FirstName, #LastName, #Email, #JobID, #SupervisorID, #HireDate, #Status)"
ProviderName="<%$ ConnectionStrings:dbConnectionString.ProviderName %>"
SelectCommand="SELECT [ID], [ClientID], [UserName], [Password], [FirstName], [LastName], [Email], [JobID], [SupervisorID], [HireDate], [Status] FROM [Users] WHERE [ID] = #ID"
UpdateCommand="UPDATE [Users] SET [ClientID] = #ClientID, [UserName] = #UserName, [Password] = #Password, [FirstName] = #FirstName, [LastName] = #LastName, [Email] = #Email, [JobID] = #JobID, [SupervisorID] = #SupervisorID, [HireDate] = #HireDate, [Status] = #StatusList WHERE [ID] = #ID">
<SelectParameters>
<asp:QueryStringParameter Name="ID" QueryStringField="curEmp" Type="Int64" />
</SelectParameters>
<UpdateParameters>
<asp:Parameter Name="ClientID" Type="Int64" />
<asp:Parameter Name="UserName" Type="String" />
<asp:Parameter Name="Password" Type="String" />
<asp:Parameter Name="FirstName" Type="String" />
<asp:Parameter Name="LastName" Type="String" />
<asp:Parameter Name="Email" Type="String" />
<asp:Parameter Name="JobID" Type="Double" />
<asp:Parameter Name="SupervisorID" Type="Double" />
<asp:Parameter Name="HireDate" Type="DateTime" />
<asp:Parameter Name="StatusList" Type="String" />
<asp:Parameter Name="ID" />
</UpdateParameters>
</asp:SqlDataSource>
Code Behind:
protected void DetailsView1_DataBound(object sender, EventArgs e)
{
if (DetailsView1.CurrentMode == DetailsViewMode.Edit)
{
DropDownList statusList = DetailsView1.FindControl("StatusList") as DropDownList;
//Add list items (later to be added by database)
if (statusList != null)
{
statusList.Items.Add(new ListItem("Select Status", ""));
statusList.Items.Add(new ListItem("Active", "Active"));
statusList.Items.Add(new ListItem("Inactive", "Inactive"));
statusList.Items.Add(new ListItem("Terminated", "Terminated"));
statusList.DataBind();
}
//Highlight selected item in dropdownlist while in edit mode
DataRowView row = (DataRowView)DetailsView1.DataItem;
ListItem liItem = statusList.Items.FindByText(row["Status"].ToString());
if (liItem != null)
{
statusList.Items.FindByText(row["Status"].ToString()).Selected = true;
}
}
}
I'm not sure where to go from here. I've tried to change the Update command in my SQLDataSource for the DropDownList (named StatusList) but haven't had any luck. Any idea what I'm missing here?
Thanks for any help!
I don't think the statusList is bound to your datasource. You would either need to bind the dropdown in the aspx or in the datasource.
So, like this in the aspx...
<asp:DropDownList ID="statusList" runat="server" SelectedValue='<%# Bind("datafield") %>'>
or in the data source parameters...
<asp:ControlParameter Name="status" ControlID="DetailsView1$statusDropDownList" PropertyName="SelectedValue" Type="String" />
I have DetailsView nested in GridView, and I can't figure out how to pass values(like ID of item in GridView and value from session) to parameters for insert method.
<asp:DetailsView ID="DetailsViewPostLikes" runat="server"
AutoGenerateRows="false" DataSourceID="odsPostLikes"
DataKeyNames="id" GridLines="None">
<Fields>
<asp:CommandField ShowInsertButton="true" InsertText="Like" newtext="Like" />
<asp:TemplateField HeaderText="" SortExpression="Nickname">
<ItemTemplate>
<asp:Label id="nicknamelikesCount" runat="server" Text='<%# Bind("LikeCount") %>'></asp:Label> people likes this.
</ItemTemplate>
</asp:TemplateField>
</Fields>
</asp:DetailsView>
<asp:ObjectDataSource ID="odsPostLikes" runat="server"
TypeName="SocWebApp.Database.PostLikeTable"
SelectMethod="Select" InsertMethod="Insert" UpdateMethod="Update">
<SelectParameters>
<asp:Parameter Name="postId" Type="Int32" />
</SelectParameters>
<InsertParameters>
<asp:Parameter Name="postId" Type="Int32" />
<asp:SessionParameter Name="userId" SessionField="User_id" Type="Int32" />
</InsertParameters>
</asp:ObjectDataSource>
I've tried to do this same way as for select parameter like this:
protected void posts_ItemDatabound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)//(GridView)e.Row.FindControl("odsComments") != null)
{
ObjectDataSource s1 = (ObjectDataSource)e.Row.FindControl("odsComments");
s1.SelectParameters["postId"].DefaultValue = DataBinder.Eval(e.Row.DataItem, "Id").ToString();
ObjectDataSource s2 = (ObjectDataSource)e.Row.FindControl("odsPostLikes");
s2.InsertParameters["postId"].DefaultValue = DataBinder.Eval(e.Row.DataItem, "Id").ToString();
ObjectDataSource s3 = (ObjectDataSource)e.Row.FindControl("odsPostLikes");
s3.InsertParameters["userId"].DefaultValue = Session["User_id"].ToString();
}
}
but only userId parameter value is set(from Session), postId is always 0.
What is the proper solution?
Thank you.
I've found the solution:
<asp:DetailsView ID="DetailsViewPostLikes" runat="server"
AutoGenerateRows="false" DataSourceID="odsPostLikes"
DataKeyNames="id" GridLines="None" OnDataBound="postLikeInsert_DataBound" OnItemCommand="postLikeInsert_ItemCommand">
<Fields>
<asp:CommandField ShowInsertButton="false" InsertText="Like" newtext="Like" />
<asp:TemplateField HeaderText="" SortExpression="Nickname">
<ItemTemplate>
<asp:LinkButton ID="Like" runat="server" CommandName="Insert" Text="Like" />
<asp:Label id="likesCount" runat="server" Text='<%# Bind("LikeCount") %>'></asp:Label> people likes this.
</ItemTemplate>
</asp:TemplateField>
</Fields>
</asp:DetailsView>
<asp:ObjectDataSource ID="odsPostLikes" runat="server"
TypeName="SocWebApp.Database.PostLikeTable"
SelectMethod="Select" InsertMethod="Insert" UpdateMethod="Update">
<SelectParameters>
<asp:Parameter Name="postId" Type="Int32" />
</SelectParameters>
<InsertParameters>
<asp:Parameter Name="postId" Type="Int32" />
<asp:SessionParameter Name="userId" SessionField="User_id" Type="Int32" />
</InsertParameters>
</asp:ObjectDataSource>
code-behind:
protected void postLikeInsert_DataBound(object sender, EventArgs e)
{
DetailsView d = (DetailsView)sender;
GridViewRow row = (GridViewRow)d.NamingContainer;
int idx = row.RowIndex;
GridView grid = (GridView)row.NamingContainer;
string strGoalIndicatorID = grid.DataKeys[idx]["id"].ToString();
LinkButton b = (LinkButton)d.FindControl("Like");
b.CommandArgument = strGoalIndicatorID;
}
protected void postLikeInsert_ItemCommand(object sender, DetailsViewCommandEventArgs e)
{
if (e.CommandName == "Insert")
{
DetailsView d = (DetailsView)sender;
d.ChangeMode(DetailsViewMode.Insert);
ObjectDataSource o = (ObjectDataSource)d.NamingContainer.FindControl("odsPostLikes");
o.InsertParameters["postId"].DefaultValue = e.CommandArgument.ToString();
}
}
when data bound, it will find the button and set his command argument to id item of parent gridview, then after hitting the button, insert parameter is set based on that command argument
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?