How to Redirect to new asp page while clicking on the data row of the data grid view in asp.net - asp.net

My data grid view in asp.net displays only selected id from sql server database as a single row.
Now I need to display a particular page when I click on the particular id (data row) and also I want to display all the details in a new page belongs to the selected id (on click on the id).
I have tried this code:
protected void btnserch_Click(object sender, EventArgs e)
{
SqlConnection objsqlconnection = new SqlConnection(CONNECTIONSTRING);
string query = "Select id from registration";
SqlCommand objsqlcommand = new SqlCommand(query, objsqlconnection);
objsqlconnection.Open();
SqlDataAdapter da=new SqlDataAdapter();
DataSet ds=new DataSet();
objsqlcommand.CommandText = query;
objsqlcommand.Connection = objsqlconnection;
da = new SqlDataAdapter(objsqlcommand);
da.Fill(ds);
objsqlcommand.ExecuteNonQuery();
GridView1.DataSource = ds;
GridView1.DataBind();
objsqlconnection.Close();
}
This code returns a grid by selecting only id column from registration table. Now when I click on the data row of the id column, I need an another page which should display all the details belonging to that id.

like #MelanciaUK said "OnItemDataBound" is your friend.
For checking ID even on postback, select it in "SelectedIndexChanging"
hope it helps.

Easiest way to redirect to new page:
<asp:GridView ID="grd" runat="server" autogeneratedcolumn="false">
<asp:TemplateField HaderText="ID">
<ItemTemplate>
<%#Eval("ID")%>
<ItemTemplate>
<asp:TemplateField>
<asp:TemplateField HaderText="Name">
<ItemTemplate>
<%#Eval("ID")%>
<ItemTemplate>
<asp:TemplateField>
<asp:TemplateField HaderText="Edit">
<ItemTemplate>
<a href='Newpage.aspx?ID=<%#Eval("ID")%>'>Edit</a>
<ItemTemplate>
<asp:TemplateField>
<asp:GridView>

You can redirect from one page another page in two ways
<asp:GridView ID="grd" runat="server" autogeneratedcolumn="false">
<asp:TemplateField HaderText="Action">
<ItemTemplate>
<a href='mypage.aspx?ID=<%#Eval("RowID")%>'>Edit</a>
Edit
<ItemTemplate>
<asp:TemplateField>
<asp:GridView>
<script type="text/javascript">
function Redirect(id) {
window.location = 'mypage.aspx?ID=' + id;
}
</script>

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

Designing notification sections in asp.net

I am trying to design a notification section for my ASP.NET website.
My requirement is similar to this image layout.
I was able to implement this with the asp repeater control and binding it with database.
I have table in my DB that has image, name and comments as its columns.
So according to the no. of rows in the DB table, the repeater control will get me the contents in the defined layout.
But i also wanted to implement the close button ("X" - top right corner). this close button will just remove the particular comment (but it will not delete data in DB).
Could you please help me in achieving this ??
Also thanks to suggest any other possible option to acheive this.
PFB the code i have done so far
<asp:Repeater ID="Repeater1" runat="server">
<ItemTemplate>
<table>
<tr>
<td style="height:64px;width:64px">
<asp:Image ID="imgEmployee" CssClass="imgClass" ImageUrl='<%# Eval("ImagePath")%>'runat="server" />
</td>
<td>
<asp:Label runat="server" Text='<%# Eval("Name")%>'></asp:Label>
<p> <%# Eval("Comments")%></p>
</td>
</tr>
</table>
</ItemTemplate>
</asp:Repeater>
and code behind
protected void Page_Load(object sender, EventArgs e)
{
DataSet ds = GetData();
Repeater1.DataSource = ds;
Repeater1.DataBind();
}
private DataSet GetData()
{
string CS = ConfigurationManager.ConnectionStrings["con"].ConnectionString;
using (SqlConnection con = new SqlConnection(CS))
{
SqlDataAdapter da = new SqlDataAdapter("Select * from tblNotification", con);
DataSet ds = new DataSet();
da.Fill(ds);
return ds;
}
}
And my table (tblNotification) has 3 columns - "ImagePath", "Name" and "Comments"

losing the first result of retrieved data when binding it to repeater control

I am developing a social network in which i must show a list of friends to the current user.
i am using SqlDataReader to retrieve data from database then bind it by a repeater , the problem is that the repeater always skip the first result so it only shows the n-1 results out of n. anybody can explain to me this behaviour?
my code is:
string cmdstr2 = "SELECT students.fname, students.lname,students.username FROM students INNER JOIN friends ON students.username = friends.tostudent WHERE (friends.fromstudent ='" + cuser + "')";
SqlCommand cmd2 = new SqlCommand(cmdstr2, sc);
SqlDataReader rd = cmd2.ExecuteReader();
if (rd.Read())
{
Repeater1.DataSource = rd;
Repeater1.DataBind();
}
in the design view, i have written this code to include the repeater in the page:
<asp:Repeater ID="Repeater1" runat="server">
<HeaderTemplate>
<div style="font-size:xx-large;">
الأصدقاء</div>
</HeaderTemplate>
<ItemTemplate>
<div style="font-size:x-large; color:Black; margin-right:0px; margin-top:0px;">
<asp:HyperLink ID="HyperLink1" runat="server"
NavigateUrl='<%# "student.aspx?user="+DataBinder.Eval(Container.DataItem,"username")%>' >
<%#DataBinder.Eval(Container.DataItem, "fname")%> <%#DataBinder.Eval(Container.DataItem, "lname")%>
</asp:HyperLink>
</div>
</ItemTemplate>
<FooterTemplate>
</FooterTemplate>
</asp:Repeater>
Your rd.Read() in your if statement is advancing it 1 record
Try using:
if (rd.HasRows)

Dropdown list to populate checkboxes

My asp.net application currently uses a Telerik RadGrid to show product data. At the top of the page, I have a dropdown list that will include 4 different categories. Based on the user's selection of category, the checkboxes in the grid will either become checked or not checked. The website's 1500 products will always show in the grid, it's the checkboxes that will be changing.
Ex: Product 1 is in Category A, therefore if a user clicks on Category B in the dropdown, the checkbox next to Product 1 will be unchecked. The only way that will be checked is if the user changes the dropdown to view the products currently in Category A.
I am having trouble trying to figure out how to approach this. For one, the line if (ProductInMarket.Checked = true) throws an error sayingThe name ProductInMarket' does not exist in the current context.` The second problem I have is that I can't figure out how to finish the UpdateMarket method. That's what happens when you take a lunch in the middle of coding. :/
This is what I have so far and I would really appreciate some help here.
<asp:DropDownList ID="MarketDropDownList" runat="server" AutoPostBack="true" OnSelectedIndexChanged="MarketDropDownList_SelectedIndexChanged" AppendDataBoundItems="true">
</asp:DropDownList>
<telerik:GridTemplateColumn AllowFiltering="true" HeaderText="Product ID" UniqueName="productid" ReadOnly="true">
<HeaderTemplate>
<asp:CheckBox ID="headerCheck" runat="server" onClick="javascript:SelectDeselectAllCheckboxes(this);" />
</HeaderTemplate>
<ItemTemplate>
<asp:Checkbox ID="ProductInMarket" runat="server" />
<asp:HiddenField runat="server" ID="ProductID" />
</ItemTemplate>
</telerik:GridTemplateColumn>
private void UpdateMarket(string MarketID)
{
//add products to market when checked
if (ProductInMarket.Checked = true)
{
string strConn = ConfigurationManager.ConnectionStrings["DBConnectingString"].ToString();
using (SqlConnection con = new SqlConnection(strConn))
{
using (SqlCommand cmd = new SqlCommand())
{
cmd.Connection = con;
cmd.CommandType = CommandType.Text;
cmd.CommandText = "UPDATE table SET ProductID = #ProductID WHERE MarketID = #MarketID";
}
}
}
}
I would recommend using batch updating via Performing Batch Operations Using DataAdapters.
Note: The UpdateBatchSize property is the key here, because it tells ADO.NET how many items to send in each batch. Setting it to zero will force the batch to be as large as possible, setting it to 1 will basically make it ignore batching, because it will send one at a time. You will need to play with this value to get the optimal value, taking into account performance and memory-usage (larger batches will use up more memory until it is cleaned up).
<asp:DropDownList ID="MarketDropDownList" runat="server" AutoPostBack="true" OnSelectedIndexChanged="MarketDropDownList_SelectedIndexChanged" AppendDataBoundItems="true">
</asp:DropDownList>
<telerik:GridTemplateColumn AllowFiltering="true" HeaderText="Product ID" UniqueName="productid" ReadOnly="true">
<HeaderTemplate>
<asp:CheckBox ID="headerCheck" runat="server" onClick="javascript:SelectDeselectAllCheckboxes(this);" />
</HeaderTemplate>
<ItemTemplate>
<asp:Checkbox ID="ProductInMarket" runat="server" />
<asp:HiddenField runat="server" ID="ProductID" />
</ItemTemplate>
</telerik:GridTemplateColumn>
private void UpdateMarket(string MarketID)
{
//add products to market when checked
if (ProductInMarket.Checked = true)
{
string strConn = ConfigurationManager.ConnectionStrings["DBConnectingString"].ToString();
using (SqlConnection con = new SqlConnection(strConn))
{
using (SqlCommand cmd = new SqlCommand())
{
cmd.Connection = con;
cmd.CommandType = CommandType.Text;
cmd.CommandText = "UPDATE table SET ProductID = #ProductID WHERE MarketID = #MarketID";
}
}
}
}
try this
jsfiddle

Displaying Data in GridView using Dataset

I am trying to display a dataset to my ASP.NET application. It seems that when I click the button event, the data is not displaying in the grid.
I have a basic page with the following:
<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server" />
<asp:UpdatePanel runat="server" id="UpdatePanel" updatemode="Conditional">
<ContentTemplate>
<asp:GridView ID="GridView1" runat="server" Width="200" Height="300">
</asp:GridView>
<asp:Button runat="server" id="UpdateButton1" onclick="UpdateButton_Click" text="Update" />
</ContentTemplate>
</asp:UpdatePanel>
</form>
Then in the code behind, I have the following:
protected void UpdateButton_Click(object sender, EventArgs e)
{
string SQLConfigSettings = ConfigurationManager.ConnectionStrings["ApplicationServices"].ConnectionString;
SqlConnection sqlconn = new SqlConnection(SQLConfigSettings);
sqlconn.Open();
SqlDataAdapter adapter = new SqlDataAdapter("Select * from Student", sqlconn);
DataSet ds = new DataSet();
adapter.Fill(ds);
GridView1.DataSource = ds;
UpdatePanel.Update();
}
Am I missing something? Shoudlnt the dataset be diaplayed in the grid?
When I click the button nothing happens.
Thanks :)
You need to add
GridView1.DataBind() right after Gridview1.DataSource.
So it becomes:
...
DataSet ds = new DataSet();
adapter.Fill(ds);
GridView1.DataSource = ds;
GridView1.DataBind();
UpdatePanel.Update();
If you need more information about the .DataBind method check MSDN on it
GridView1.DataSource = ds;
Try to mention table inside dataset. Something like ds.Tables[0] or if you know name of table ds.Tables["table_name"]
Put a breakpoint on the first line of code in UpdateButton_Click and run it.
Is that breakpoint reached?
Step through each line of code after that and examine the variable values. Is the DataSet being filled? Can you see the DataTable and its DataRows?
If you reach this event code and have data, then you need to look at the databinding. You need to do GridView.DataBind() immediately after setting the DataSource and before doing the UpdatePanel.Update(). Then you should be good to go.

Resources