add date to database if checkbox checked in gridview - asp.net

I have an Ordering system showing Orders that have been received and also orders that are outstanding. If the Order is received and the checkbox is then checked I would like to add the date to the database when the order was received. Obviously I would only like to add the date to the row that has been checked. Thanks in advance.
relevant HTML as follows:
<asp:GridView ID="gvOpenOrders" runat="server" AutoGenerateColumns="False" Width="100%" CellPadding="4" ForeColor="#333333"
GridLines="None" DataKeyNames="PurchaseOrderID" AllowPaging="True" AllowSorting="True"
OnSorting="gvOpenOrders_Sorting" EnableViewState="true" OnPageIndexChanging="OnPageIndexChanging" PageSize="15" ViewStateMode="Enabled">
<AlternatingRowStyle BackColor="White" />
<Columns>
<asp:TemplateField HeaderText="Is Received" SortExpression="IsReceived">
<ItemTemplate>
<asp:CheckBox ID="chkRcvd" runat="server" AutoPostBack="true" Checked='<%# Bind("IsReceived") %>' Enabled='<%# Eval("IsReceived") = False %>' OnCheckedChanged="chkRcvd_CheckedChanged" />
</ItemTemplate>
</asp:TemplateField>
I am currently updating the database when a Update Received button is clicked, see below:
Protected Sub btnUpdateReceived_Click(sender As Object, e As EventArgs) Handles btnUpdateReceived.Click
con.Open()
For Each row As GridViewRow In gvOpenOrders.Rows
Dim purchaseOrderID As Integer = Convert.ToInt32(gvOpenOrders.DataKeys(row.RowIndex).Values(0))
Dim isReceived As Boolean = TryCast(row.FindControl("chkRcvd"), CheckBox).Checked
cmd.CommandText = "usp_UpdatePurchaseOrder"
cmd.CommandType = CommandType.StoredProcedure
cmd.Parameters.Clear()
cmd.Parameters.AddWithValue("#OrderID", purchaseOrderID)
cmd.Parameters.AddWithValue("#IsReceived", isReceived)
cmd.ExecuteNonQuery()
Next
con.Close()
Response.Redirect(Request.Url.AbsoluteUri)
End Sub
I know that there is a checkbox_CheckedChanged event but I am unsure how to use it.

You can add this code in CheckedChanged event:
CheckBox chkSelect = (CheckBox)sender;
if (chkSelect.Checked)
{
string date = DateTime.Today.ToString("dd-MM-yyyy");
}
Hope could convert it into VB's code.

As I think only one modification can find your solution.
Try this:
string strDate=stirng.Empty;
foreach (GridViewRow rw in grid1.Rows)
{
CheckBox chkBx = (CheckBox)rw.FindControl("Check");
if (chkBx != null && chkBx.Checked)
{
strDate = ((Label)rw.FindControl("lblDate")).Text;
}
}

protected void chkRcvd_CheckedChanged(object sender, EventArgs e)
{
CheckBox chkSelect = (CheckBox)sender;
if (chkSelect.Checked)
{
string date = DateTime.Today.ToString("dd-MM-yyyy");
}
}

Related

How to update database in SQL Server when I have checkbox in gridview?

I tried to make a message board.
After someone leave message, manager can check message context can be show for others or not.
I use gridView to connect to my SQL Server data, and there is a checkbox in the gridview.
If I checked checkbox, and click "sent" button, SQL Server data will be updated.
If I would like to update checkbox result into SQL Server data, what should I do?
This is my aspx
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataKeyNames="id" OnRowDeleting="GridView1_RowDeleting">
<Columns>
<asp:TemplateField HeaderText="check or not" SortExpression="replyCheck">
<EditItemTemplate>
<asp:CheckBox ID="CheckBox1" runat="server" Checked='<%# Bind("replyCheck") %>' />
</EditItemTemplate>
<ItemTemplate>
<asp:CheckBox ID="CheckBox2" runat="server" Checked='<%# Bind("replyCheck") %>' Enabled="True" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<br/>
<asp:Button ID="Button1" runat="server" Text="sent" OnClick="Button1_Click"/>
And this is my aspx.cs - if I use foreach, it can't update into my database
protected void Button1_Click(object sender, EventArgs e)
{
var id = GridView1.DataKeys.ToString();
foreach (GridViewRow row in GridView1.Rows)
{
CheckBox reply = (row.Cells[0].FindControl("CheckBox2") as CheckBox);
if (reply.Checked)
{
SqlConnection sqlConnection = new SqlConnection(getsql);
sqlConnection.Open();
SqlCommand cmd = new SqlCommand($"UPDATE reply SET replyCheck ='1' WHERE (id = {id})", sqlConnection);
cmd.ExecuteNonQuery();
sqlConnection.Close ();
DataBind();
}
}
}
If I use for, it showed error about "datakey array"
protected void Button1_Click(object sender, EventArgs e)
{
var id = GridView1.DataKeys.ToString();
int messageCheck, displayCheck;
SqlConnection sqlConnection = new SqlConnection(getsql);
sqlConnection.Open();
for (int i = 0; i < GridView1.Rows.Count; i++)
{
CheckBox message = (CheckBox)GridView1.Rows[i].FindControl("CheckBox2");
if (message.Checked == true)
{
messageCheck = 1;
SqlCommand cmd1 = new SqlCommand($"UPDATE reply SET replyCheck = {messageCheck} WHERE (id = {id})", sqlConnection);
cmd1.ExecuteNonQuery();
}
else
{
messageCheck = 0;
SqlCommand cmd2 = new SqlCommand($"UPDATE reply SET replyCheck = {messageCheck} WHERE (id = {id})", sqlConnection);
cmd2.ExecuteNonQuery();
}
}
sqlConnection.Close();
}
Without javascript, how could I do it?
Thanks for you all
Ok, the way this works is that datafields (non templated columns) in the GV use the cells[] collection.
However, for templated columns, we have to use find control.
And also we will use the data keys feature, as that lets us have/use/work with the database PK row ID, but NOT have to display in the markup/grid for users.
Ok, so here is a GV with both datafiles (the cells()), and also check box.
We will select the check boxes, and then with a save button, send changes back to database.
So, our markup:
<div style="width:50%;padding:25px">
<asp:GridView ID="GVHotels" runat="server" class="table borderhide"
AutoGenerateColumns="false" DataKeyNames="ID">
<Columns>
<asp:BoundField DataField="FirstName" HeaderText="FirstName" />
<asp:BoundField DataField="LastName" HeaderText="LastName" />
<asp:BoundField DataField="City" HeaderText="City" />
<asp:BoundField DataField="HotelName" HeaderText="HotelName" HeaderStyle-Width="200" />
<asp:BoundField DataField="Description" HeaderText="Description" />
<asp:TemplateField HeaderText="Smoking" ItemStyle-HorizontalAlign="Center" >
<ItemTemplate>
<asp:CheckBox ID="chkSmoking" runat="server"
Checked='<%# Eval("Smoking") %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Balcony" ItemStyle-HorizontalAlign="Center" >
<ItemTemplate>
<asp:CheckBox ID="chkBalcony" runat="server"
Checked='<%# Eval("Balcony") %>' />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<asp:Button ID="cmdSave" runat="server" Text="Save changes" CssClass="btn"/>
</div>
And now our code to fill out above could be say this:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
LoadGrid();
}
void LoadGrid()
{
using (SqlConnection con = new SqlConnection(Properties.Settings.Default.TEST4))
{
using (SqlCommand cmdSQL =
new SqlCommand("SELECT * from tblHotels ORDER BY HotelName ", con))
{
con.Open();
GVHotels.DataSource = cmdSQL.ExecuteReader();
GVHotels.DataBind();
}
}
}
And now we see this:
Now, there is two ways we can update the database. We could in fact update using a datatable, and in one whole shot upate the datbase.
but, we just loop the GV, and execute updates. (if I have time, I'll try and post the 2nd more cool approach).
So, our button to update/save changes (for check boxes). Could be this:
protected void cmdSave_Click(object sender, EventArgs e)
{
using (SqlConnection conn = new SqlConnection(Properties.Settings.Default.TEST4))
{
conn.Open();
string strSQL = "UPDATE tblHotels Set Smoking = #S, Balcony = #B " +
"WHERE ID = #ID";
foreach (GridViewRow gRow in GVHotels.Rows)
{
CheckBox cSmoke = (CheckBox)gRow.FindControl("chkSmoking");
CheckBox cBlacony = (CheckBox)gRow.FindControl("chkBalcony");
int PKID = (int)GVHotels.DataKeys[gRow.RowIndex]["ID"];
using (SqlCommand cmdSQL = new SqlCommand(strSQL, conn))
{
cmdSQL.Parameters.Add("#S", SqlDbType.Bit).Value = cSmoke.Checked;
cmdSQL.Parameters.Add("#B", SqlDbType.Bit).Value = cBlacony.Checked;
cmdSQL.Parameters.Add("#ID", SqlDbType.Int).Value = PKID;
cmdSQL.ExecuteNonQuery();
}
}
}
}
Note how we use row index to get the PK row ID. NOTE the DataKeys setting for the GV. This allows you to use/have/enjoy use of the database PK row ID (named "ID" in this code example), and NOT have to display/include the PK in the GV display.
Note that you would continue to use cells() collection for NON templated columns. But for any templated column - you have to use FindControl on that row, pluck out the control, and then you can have at it in regards to that control value.
We could also pull each GV row into a data table, and execute ONE datatable update into the database. But, as the above code shows - we actually keep the connection open for the update - and thus not a big deal either way.
Kindly check with this code
Protected Sub Button1_Click(sender As Object, e As EventArgs)
For Each row In GridView1.Rows
Dim chk As CheckBox = row.FindControl("CheckBox2")
If chk.Checked Then
'sql update query
Else
End If
Next
End Sub

Get a CheckBox to command a GridView row

I have a GridView holding my order table (these are inserted values from an insert statement). The order table appears on the doctor page, but I want to add to it so it can be approve/unapproved (if checked then update the 'Approve' column to approved, if not checked update the 'Approve' column to not approved. I need to add a CheckBox column to the GridView for this. This is part of my learning (not a live website).
How do I add a column of check boxes to a GridView that would set a row to approve/unapproved when checked?
This is my order table -(all the data is dummy data)
Grid:
<asp:GridView ID="GridViewdoc" runat="server" >
</asp:GridView>
Showing the data on the grid
Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
If Not IsPostBack Then
Dim conn As New System.Data.SqlClient.SqlConnection("Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\surgerydb.mdf;Integrated Security=True;Connect Timeout=30")
Dim cmd3string As String = " Select * From alltheview WHERE DoctorId = " & Session("DoctorId")
Dim dt As New System.Data.DataTable()
Dim da As New System.Data.SqlClient.SqlDataAdapter(cmd3string, conn)
conn.Open()
da.Fill(dt)
conn.Close()
GridViewdoc.DataSource = dt
GridViewdoc.DataBind()
End If
End Sub
My select statement that pulls the data:
Create View theallview
As
Select A.OrderID
,A.PatientId ,B.Forename,B.Surname ,A.MedicineId ,C.Name as MedicineName ,E.Name as DoctorName, A.PharmacyId ,D.pharmname ,A.DoctorId ,A.Dateordered, Approved
From order_pres A
Left Join Patient B on (A.PatientId = B.PatientId)
Left Join Medicine C on (A.MedicineId = C.MedicineId)
Left Join pharmacy D on (A.PharmacyId = D.PharmacyId)
Left Join Doctor E on (A.DoctorId = E.DoctorId)
How the order table now looks (this is all dummy data by the way:
A button . click event will then submit the checked values
If anyone needs more information regarding this question please let me know.
Try this. It's in C# but you should be able to work out the VB.Net pretty easily.
As an aside I would put your code to load your data in its own method. Once the approved is updated I would recommend reloading your grid view.
ASPX:
<asp:GridView ID="GridViewdoc" DataKeyNames="OrderId" AutoGenerateColumns="false" runat="server">
<Columns>
<asp:BoundField HeaderText ="Order Id" DataField="OrderId" />
<asp:BoundField HeaderText ="Patient Id" DataField="PatientId" />
<asp:BoundField HeaderText ="Medicine Id" DataField="MedicineId" />
<asp:BoundField HeaderText ="Pharmacy Id" DataField="PharmacyId" />
<asp:BoundField HeaderText ="Doctor Id" DataField="DoctorId" />
<asp:BoundField HeaderText ="Date Ordered" DataField="Dateordered" />
<asp:TemplateField HeaderText="Approve/Unapprove">
<ItemTemplate>
<asp:CheckBox ID="chkApproved" AutoPostBack="true" Checked='<%# Eval("Approved") == null || Eval("Approved") == DBNull.Value ? false : Eval("Approved") %>' runat="server" OnCheckedChanged="chkApproved_CheckedChanged" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Code behind:
protected void chkApproved_CheckedChanged(object sender, EventArgs e)
{
CheckBox chkApproved = (CheckBox)sender;
GridViewRow gridViewRow = (GridViewRow)chkApproved.Parent.Parent;
int orderID = (int)GridViewdoc.DataKeys[gridViewRow.RowIndex].Value;
bool approved = chkApproved.Checked;
//Your update method
UpdateApproved(orderID, approved);
//Your data load method
LoadData();
}

I need to use Checkboxlist within a GridView which binds data from other table

I have to fill checkboxlist which is within the gridview control.
<asp:GridView ID="gvProject" CssClass="Gridview viewproject-th-col-remov" runat="server" AutoGenerateColumns="false" OnRowDataBound="gvProject_RowDataBound" DataKeyNames="ProjectID" AllowPaging="True">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:LinkButton ID="lnkContract" runat="server" Text="Contract" ControlStyle-CssClass="pdf-download-link"OnClick="DownloadFile" CommandArgument='<%# Eval("ProjectId") %>'></asp:LinkButton>
<asp:CheckBoxList ID="chkAdSpace" runat="server"></asp:CheckBoxList>
</ItemTemplate>
</asp:TemplateField>
</Columns> </asp:GridView>
Then I have bound the data in checkboxlist like this.
private void BindList(Int32 _id)
{
DataTable dtAdSpace = new DataTable();
dtAdSpace = CommonDataViews.GetAdSpaceSearch(_id);
if (dtAdSpace.Rows.Count > 0)
{
chkAdSpace.DataSource = dtAdSpace;
chkAdSpace.DataTextField = "adspace";
chkAdSpace.DataValueField = "adspace";
chkAdSpace.DataBind();
}
}
But, problem is chkASpace does not accessible int BindList(Int32 _id) or throught the form. Please help me why this is not accessible like LinkButton which I used.
Thanks in advance.
Raja
Retrieve the data to bind in a DataTable.
In GridView_RowDataBound event, Bind the Checkboxlist with the DataTable. Get the Checkboxlist by using FindControl. Like below:
protected void gvProject_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
CheckBoxList cblProject = (CheckBoxList)e.Row.FindControl("chkAdSpace");
cblProject.DataSource = dtAdSpace;
cblProject.DataTextField = "adspace";
cblProject.DataValueField = "adspace";
cblProject.DataBind();
}
}
I think the question was how to do it within ASP.net and not from code behind.
ie: Gridview binds to a datasource, but within the gridview there is a column with a checkboxlist and its own datasource. Using Eval("yourcolumn") tries to bind to the main datasource of the GridView and not the checkboxlist.
Sorry I do not have the answer, as I am trying to determine that as well.
To Check All the ckeckboxes in the list simply iterate through each checkbox to check them.After Databind.
foreach (ListItem listItem in chkAdSpace.Items)
{
listItem.Selected = true;
}
Here is my answer:
The GridView code is:
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
DataKeyNames="id" DataSourceID="SqlDataSource1"
OnRowDataBound="GridView1_RowDataBound">
<Columns>
<asp:BoundField DataField="id" HeaderText="id" InsertVisible="False" ReadOnly="True" SortExpression="id" />
<asp:BoundField DataField="name" HeaderText="name" SortExpression="name" />
<asp:TemplateField HeaderText="Subjects">
<ItemTemplate>
<asp:CheckBoxList ID="CheckBoxList1" runat="server" DataTextField="fprefid" DataValueField="fprefid">
</asp:CheckBoxList>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Here is the C# code:
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
CheckBoxList cbl = (CheckBoxList)e.Row.FindControl("CheckBoxList1");
object objTemp = GridView1.DataKeys[e.Row.RowIndex].Value as object;
string id = objTemp.ToString();
SqlConnection con1 = new SqlConnection(constr);
SqlConnection con2 = new SqlConnection(constr);
SqlCommand com1 = new SqlCommand("select prefid from preferences",con1);
if (con1.State == ConnectionState.Closed)
con1.Open();
if (con2.State == ConnectionState.Closed)
con2.Open();
SqlDataReader dreader1 = com1.ExecuteReader();
if(dreader1.HasRows)
{
while(dreader1.Read())
{
SqlCommand com2 = new SqlCommand("select fprefid from person_pref where fpersonid='" + id + "' and fprefid = '" + dreader1["prefid"] + "'", con2);
SqlDataReader dreader2 = com2.ExecuteReader();
ListItem li = new ListItem();
if (dreader2.HasRows)
{
li.Text = dreader1["prefid"].ToString();
li.Selected = true;
}
else
{
li.Text = dreader1["prefid"].ToString();
li.Selected = false;
}
cbl.Items.Add(li);
dreader2.Close();
}
}
}
}

Dropdownlists with parent-child relation in EditItemTemplate Gridview not working

I have a page with gridview in it.
My gridview shows the products Information and Admin can Edit gridviews columns.
Two of my columns show the brand name and category name for each product;
I use lables in ItemTemplate tag in my grid view to show these two columns value and I use two dropdownlists(branddrop,categorydrop)
in my EditItemTemplate tag for editing these two columns value,when admin select an item in branddrop the categorydrop should show categories name which are related to selected brand name in branddrop.
Brands name in my brand table in database are:
Samsung, Nokia,Sony Ericsson,Apple,LG,HTC....
and my categories name in category table are :
Galaxy Nexus,Galaxy Tab 2 7. 0,Galaxy S3,Asha,Lumia,iPhone,iPad,Xperia Arc,Xperia Neo,Xperia X8,Cookie 3g,Cookie lite,Km555e,Optimus l9,Optimus elite,Optimus g,wt18i,w8,500,n8...
When I click the Edit button, first item in the branddrop is Equal to brandlable.
Text in ItemTemplate and it works fine my problem is the first item in category drop is not Equal to categorylable.text in ItemTemplate and the category drop does not show the related categories name to brandname.for every product it shows iphone and ipad so I have to select another items in branddrop and then select again the related brandname which is related to that product then the categorydrop can show the list of related categories name.I tried to use brandDrop_SelectedIndexChanged and GridView1_RowEditing but it is not work. I dont know how to solve it.
this is my first code:
<asp:TemplateField HeaderText="brand name">
<ItemTemplate>
<asp:Label ID="brandname" runat="server" Text='<%#Eval("brand_name") %>'></asp:Label>
<asp:Label ID="idfrombrand" runat="server" Text='<%#Eval("idfrombrands") %>' Visible="false"></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:Label ID="br" runat="server" Text='<%# Eval("idfrombrands") %>' Visible="false"></asp:Label><%--OnSelectedIndexChanged="brandDrop_SelectedIndexChanged" --%>
<asp:DropDownList ID="brandDrop" runat="server" DataTextField="brand_name" DataValueField="id" DataSourceID="SqlDataSource4" AutoPostBack="true" OnSelectedIndexChanged="brandDrop_SelectedIndexChanged" >
</asp:DropDownList>
<asp:SqlDataSource ID="SqlDataSource4" runat="server" ConnectionString="<%$ ConnectionStrings:mobile_storeConnectionString2 %>" SelectCommand="select [id],[brand_name] from [brands]" ></asp:SqlDataSource>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="category name">
<ItemTemplate>
<asp:Label ID="catname" runat="server" Text='<%# Eval("category_name") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:Label ID="OldCatName" runat="server" Text='<%# Eval("idfromCategories") %>' Visible="false"></asp:Label>
<asp:DropDownList ID="categoryDrop" runat="server" AutoPostBack="true" DataTextField="category_name" DataValueField="id" DataSourceID="SqlDataSource3"> <%-- --%>
</asp:DropDownList>
<asp:Label ID="cat" runat="server" Text='<%# Eval("idfromCategories") %>' Visible="false" ></asp:Label>
<asp:SqlDataSource ID="SqlDataSource3" runat="server" ConnectionString="<%$ ConnectionStrings:mobile_storeConnectionString2 %>" SelectCommand="select [category_name],[id],[idfrombrands] from [categories] where idfrombrands=#idfrombrands " >
<SelectParameters>
<asp:ControlParameter ControlID="brandDrop"
Name="idfrombrands" PropertyName="SelectedValue" Type="Int32" />
</SelectParameters>
</asp:SqlDataSource>
</EditItemTemplate>
</asp:TemplateField>
this is my code behind for GridView1_RowDataBound and GridView1_RowUpdating:
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
int brand=0;
int category=0;
//Drop Brand--------------------------------------
DropDownList list1 = (DropDownList)GridView1.Rows[e.RowIndex].FindControl("brandDrop");
Label lbl = (Label)GridView1.Rows[e.RowIndex].FindControl("br");
if (list1.SelectedItem.Value != null)
{
brand = Convert.ToInt32(list1.SelectedItem.Value);//NewIdFromBrand
}
else
{
brand = Convert.ToInt32(lbl.Text);
}
//Drop Category----------------------------------------
DropDownList list2 = (DropDownList)GridView1.Rows[e.RowIndex].FindControl("categoryDrop");
Label lbl2 = (Label)GridView1.Rows[e.RowIndex].FindControl("OldCatName");
//int NewIdFromBrand2 = -1;
if (list2.SelectedItem.Value != null)
{
category = Convert.ToInt32(list2.SelectedItem.Value);//NewIdFromBrand2
}
else
{
category = Convert.ToInt32(lbl2.Text);
}
//Photo-------------------------------------------
string photoname = System.Guid.NewGuid().ToString();
GridViewRow row = GridView1.Rows[e.RowIndex];
FileUpload fileUpload = row.FindControl("FileUploadimg") as FileUpload;
Label lbl3 = (Label)GridView1.Rows[e.RowIndex].FindControl("oldImage");
if (fileUpload != null && fileUpload.HasFile)
{
fileUpload.SaveAs(Server.MapPath("~/P_Image") + photoname + fileUpload.FileName);
SqlDataSource1.UpdateParameters["path"].DefaultValue = "~/P_Image" + photoname + fileUpload.FileName;
}
else
{
SqlDataSource1.UpdateParameters["path"].DefaultValue = lbl3.Text;//oldImage.Text;
}
int prid = Convert.ToInt32(GridView1.DataKeys[e.RowIndex].Value);
SqlConnection cn = new SqlConnection();
cn.ConnectionString = "server = . ; database = mobile_store ; Trusted_Connection=true";
DataTable tb = new DataTable();
SqlCommand cmd = new SqlCommand();
cmd.Connection = cn;
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "UpdateProduct";
cmd.Parameters.AddWithValue("#brandid", brand );
cmd.Parameters.AddWithValue("#catid", category );
cmd.Parameters.AddWithValue("#pid", prid);
try
{
cn.Open();
cmd.ExecuteNonQuery();
SqlDataSource1.DataBind();
}
catch (Exception ex2)
{
}
finally { cn.Close(); }
//GridView1.EditIndex = -1;
//GridView1.DataBind();
}
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
//check if is in edit mode
if ((e.Row.RowState & DataControlRowState.Edit) > 0)
{
DataRowView dRowView1 = (DataRowView)e.Row.DataItem;
if (e.Row.RowType == DataControlRowType.DataRow)
{
if ((e.Row.RowState & DataControlRowState.Edit) > 0)
{
DropDownList ddlStatus = (DropDownList)e.Row.FindControl("brandDrop");
ddlStatus.SelectedValue = dRowView1["brandId"].ToString();
DropDownList ddlStatus2 = (DropDownList)e.Row.FindControl("categoryDrop");
ddlStatus2.SelectedValue = dRowView1["categoryID"].ToString();
//Label1.Text = ddlStatus.SelectedValue;
}
}
}
}
}
Thank you so much Abide Masaraure.you helped me a lot.
I deleted grideview_rowediting and braddrop_selectedIndexChange event And just added two lines to my GridView1_RowDataBound event.
SqlDataSource sq = (SqlDataSource)e.Row.FindControl("SqlDataSource3");
sq.SelectParameters["idfrombrands"].DefaultValue = dRowView1["brandId"].ToString();
now my event is like this:
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
//check if is in edit mode
if ((e.Row.RowState & DataControlRowState.Edit) > 0)
{
DataRowView dRowView1 = (DataRowView)e.Row.DataItem;
if (e.Row.RowType == DataControlRowType.DataRow)
{
if ((e.Row.RowState & DataControlRowState.Edit) > 0)
{
DropDownList ddlStatus = (DropDownList)e.Row.FindControl("brandDrop");
ddlStatus.SelectedValue = dRowView1["brandId"].ToString();
DropDownList ddlStatus2 = (DropDownList)e.Row.FindControl("categoryDrop");
ddlStatus2.SelectedValue = dRowView1["categoryID"].ToString();
SqlDataSource sq = (SqlDataSource)e.Row.FindControl("SqlDataSource3");
sq.SelectParameters["idfrombrands"].DefaultValue = dRowView1["brandId"].ToString();
}
}
}
}
}
Eureka!!!.You owe me a cup of coffee.I replicated your problem and realized after two hours that you need to actually hook to your index selected changed event.The trick is to use the naming container property to locate your drop downs,they think are pretty hidden ,but the sender argument enables us to expose them when dropband dropdown fires. And presto everything works like a charm.
Use this code snipet in your selected changed event.
protected void dropBand_SelectedIndexChanged(object sender, System.EventArgs e)
{
DropDownList dropBand = (DropDownList)sender;
SqlDataSource dsc = (SqlDataSource)dropBand.NamingContainer.FindControl("SqlDataSource3");
DropDownList categoryDrop = (DropDownList)dropBand.NamingContainer.FindControl("categoryDrop");
dsc.SelectParameters("BrandID").DefaultValue = dropBand.SelectedValue;
categoryDrop.DataBind();
}
I can send you a zip file of the demo this time if you happen to continue having issue.Happy Coding!!!.
I need to see your code you are using in your selected index changed event.
The following cascading drop down technique will take away all the suffering you have in trying to hook up the parent and its children...I use this wonderful feature in the Ajax control toolkit in all my projects.You can use any data retrieval method you want as long it returns an array.I am using linq in this example for data retrieval.
Assuming I have tables named Brand and Model and classes : Brand and Model and collections: Brands and Models
In 'YourWebServicePath.asmx' (Web service file)
<WebMethod()> _
Public Function GetBrands(knownCategoryValues As String, category As String) As CascadingDropDownNameValue()
Dim result = From b As Bands In Brand.Brands Select New CascadingDropDownNameValue(b.BrandDesc, b.BrandID.ToString())
Return result.ToArray()
End Function
<WebMethod()> _
Public Function GetModels(knownCategoryValues As String, category As String) As CascadingDropDownNameValue()
Dim brandID As Guid
Dim brandValues As StringDictionary = AjaxControlToolkit.CascadingDropDown._
ParseKnownCategoryValuesString(knownCategoryValues)
brandID = New Guid(brandValues("Brand"))
Dim result = From m As Models In Model.GetModels() Where m.brandID = brandID Select New CascadingDropDownNameValue(m.ModelDesc,
_ m.ModelID.ToString())
Return result.ToArray()
End Function
MarkUp
<%# Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="cc1" %>
<EditItemTemplate>
<asp:DropDownList ID="dropBrand" runat="server" AutoPostBack="true" >
</asp:DropDownList>
<cc1:CascadingDropDown ID="BrandCascadingDropDown"
runat="server"
Category="Brand"
TargetControlID="dropBrand"
PromptText="-Select Brand-"
LoadingText="Loading Brands.."
ServicePath="YourWebServicePath.asmx"
ServiceMethod="GetBrands">
</cc1:CascadingDropDown>
</EditItemTemplate>
<EditItemTemplate>
<asp:DropDownList ID="dropModel" runat="server" AutoPostBack="true" >
</asp:DropDownList>
<cc1:CascadingDropDown ID="ModelCascadingDropDown"
runat="server"
Category="Model"
TargetControlID="dropModel"
ParentControlID="dropBrand"
PromptText="-Select Model-"
LoadingText="Loading Models.."
ServicePath="YourWebServicePath.asmx"
ServiceMethod="GetModels" >
</cc1:CascadingDropDown>
And thats all you need.No need of wiring the events.And voila! let the toolkit perform the magic.
To use the above code i gave you in a row editing event you have to modify it like so.Then those objects won't be null.
protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
{
GridView testgrid = (GridView)(sender);
testgrid.EditIndex = e.NewEditIndex;
testgrid.DataBind();
DropDownList dropBand = (DropDownList)testgrid.Rows[e.NewEditIndex].FindControl("ddlProducts");
//
}
Something is definitely happening in your page cycle and is keeping on biting you.I suggest zip an mdf of your database and the offending aspx page and let me tackle it from here if you don't get it to work.Never give up.

GridView RowCommand Event and Saving Text

I have a GridView set up:
<asp:GridView id="GridView1" Runat="server" AutoGenerateColumns="False" OnRowCommand = "GridView1_RowCommand" EnableViewState="true">
<Columns>
<asp:TemplateField HeaderText="Delete" ItemStyle-HorizontalAlign="Center">
<ItemTemplate><asp:Button runat="server" ID="Delete" ImageUrl="~/images/Close.gif" CommandName="DeleteRow" CommandArgument="<%# CType(Container,GridViewRow).RowIndex %>"/></ItemTemplate></asp:TemplateField>
<asp:TemplateField HeaderText="Comment" ItemStyle-Width="175px">
<ItemTemplate><textarea class="raTextBox" id="txtItemComment" rows="4" cols="30"></textarea></ItemTemplate></asp:TemplateField>
</Columns>
</asp:GridView>
The RowCommand in code-behind is setup like:
Protected Sub GridView1_RowCommand(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewCommandEventArgs)
If (e.CommandName = "DeleteRow") Then
//do stuff here
The GridView is data bound on Page Load as follows:
Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
If Not IsPostBack Then
Session("CalledModule") = "RCMT0021"
Else
With ViewState
_intRepor = CInt(.Item("Report"))
End With
End If
DataBind() //Gridview Load
End Sub
My questions:
The row command event is never fired. The page just goes into the ELSE (of Not is Postback) in Page_Load
How can I keep track of what all is typed in the "Comments" column of each row (a TEXTAREA), and save the data to the database when a SAVE CHANGES (form) button is clicked?
Thanks!
UPDATE:
The Grid-View's Databinding is as follows:
Public Sub DataBind()
Dim clsDatabase As New clsDatabase
Dim cmd As New OleDbCommand()
Try
cmd.CommandText = "SELECT A, B FROM WHERE C = ? ORDER BY A"
Dim report As New OleDbParameter("#Report", _intReportNumber)
cmd.Parameters.Add(report)
cmd.Connection = clsDatabase.Open_DB()
Dim dReader As OleDbDataReader
dReader = cmd.ExecuteReader(CommandBehavior.CloseConnection)
Dim dt As New DataTable
dt.Columns.Add(New DataColumn("PictureURL", GetType(String)))
dt.Columns.Add(New DataColumn("Seq", GetType(Int16)))
dt.Columns.Add(New DataColumn("ReportNumber", GetType(String)))
Do While (dReader.Read())
Dim dr As DataRow = dt.NewRow()
_strComments = dReader(0).ToString
dr("Seq") = dReader.GetInt16(1)
dr("PictureURL") = "GetImages.aspx?report=" + _intReportNumber.ToString + "&seq=" + dReader.GetInt16(1).ToString
dr("ReportNumber") = _intReportNumber.ToString
dt.Rows.Add(dr)
Loop
GridView1.DataSource = dt
GridView1.DataBind()
Catch err As Exception
End Try
End Sub
So basically, the GridView has three visible columns - a comments field, a picture field, and a field with a delete button (image) to delete the picture (and comments, if any) from the database. The 4th column is a hidden one, keeping track of the the Image ID of the images. I didn't include the picture and other columns for simplicity sake.
The user can add comments, and when he clicks a 'SAVE CHANGES' button, the corresponding comments should get saved for the picture.
The 'SELECT IMAGE' opens up a ModalDialogBox which enables the user to select the image. When closed, it causes a postback, and rebinds the gridview to display the image the user just selected. Therefore, I need the GridView to rebind on postback, or a way around this.
The delete imagebutton (in gridview) should delete the image and comments from the database.
Thanks again!
try this structure...
aspx page: (note textarea has runat="server")
<body>
<form runat="server">
<asp:ScriptManager runat="server" />
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" OnRowCommand="GridView1_RowCommand"
EnableViewState="true" OnRowDataBound="GridView1_RowDataBound">
<Columns>
<asp:TemplateField HeaderText="Delete" ItemStyle-HorizontalAlign="Center">
<ItemTemplate>
<asp:Button runat="server" ID="Delete" Text="Delete" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Comment" ItemStyle-Width="175px">
<ItemTemplate>
<textarea runat="server" class="raTextBox" id="txtItemComment" rows="4" cols="30"></textarea></ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</ContentTemplate>
</asp:UpdatePanel>
</form>
</body>
aspx.cs:
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
BindGrid();
}
}
protected void BindGrid()
{
var items = new List<string>();
for (int i = 0; i < 10; i++)
{
items.Add(i + ";comment" + i.ToString());
}
GridView1.DataSource = items;
GridView1.DataBind();
}
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "DeleteRow")
{
var idx = Convert.ToInt32(e.CommandArgument);
var cmt = GridView1.Rows[idx].FindControl("txtItemComment") as System.Web.UI.HtmlControls.HtmlTextArea;
cmt.Value = DateTime.Now.ToString();
}
}
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
var item = e.Row.DataItem.ToString().Split(";".ToCharArray());
var del = e.Row.FindControl("Delete") as Button;
del.CommandName = "DeleteRow";
del.CommandArgument = item[0];
var cmt = e.Row.FindControl("txtItemComment") as System.Web.UI.HtmlControls.HtmlTextArea;
cmt.Value = item[1];
}
}

Resources