I am trying to insert data from my radGrid that has some data to my sql. in my rad grid i also have a check box column so i want the checked rows to be inserted in my db. i am using the code below but gives me this error:
Error 30 'Telerik.Web.UI.RadGrid' does not contain a definition for 'Rows' and no extension method 'Rows' accepting a first argument of type 'Telerik.Web.UI.RadGrid' could be found (are you missing a using directive or an assembly reference?) any idea where i am doing wrong???
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
this.BindGrid();
}
}
private void BindGrid()
{
string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand("SELECT [ReportId], [Report], [IsSelected] FROM Hobbies"))
{
using (SqlDataAdapter sda = new SqlDataAdapter())
{
cmd.Connection = con;
sda.SelectCommand = cmd;
using (DataTable dt = new DataTable())
{
sda.Fill(dt);
RadGrid1.DataSource = dt;
RadGrid1.DataBind();
}
}
}
}
}
protected void Rows()
{
}
protected void Save2_Click(object sender, EventArgs e)
{
try
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["Rights"].ConnectionString);
string insert = "insert into Rights(Name,Mbiemri,Gjinia,Departamenti,Mosha,IntRights,Transferta,Depozita,Rapore) values (#Name,#Mbiemri,#Gjinia,#Departamenti,#Mosha,#IntRights,#Transferta,#Depozita,#Rapore)";
SqlCommand cnd = new SqlCommand(insert, con);
con.Open();
foreach (GridViewRow row in RadGrid1.Rows)
{
//Get the HobbyId from the DataKey property.
int ReportID = Convert.ToInt32(GridView1.DataKeys[row.RowIndex].Values[0]);
//Get the checked value of the CheckBox.
bool isSelected = (row.FindControl("chkSelect") as CheckBox).Checked;
//Save to database
cmd.Parameters.Clear();
cmd.Parameters.AddWithValue("#ReportId", ReportID);
cmd.Parameters.AddWithValue("#IsSelected", isSelected);
cmd.ExecuteNonQuery();
}
cnd.Parameters.AddWithValue("#Name", TextBox1.Text);
cnd.Parameters.AddWithValue("#Mbiemri", TextBox2.Text);
cnd.Parameters.AddWithValue("#Gjinia", RadioButtonList1.SelectedValue);
cnd.Parameters.AddWithValue("#Departamenti", SelectDepartament.SelectedItem.Text);
cnd.Parameters.AddWithValue("#Mosha", RadDropDownList1.SelectedItem.Text);
cnd.Parameters.AddWithValue("#IntRights", RadDropDownList2.SelectedItem.Text);
cnd.Parameters.AddWithValue("#Transferta", TransfertaBtn.SelectedValue);
cnd.Parameters.AddWithValue("#Depozita", DepoziteBtn.SelectedValue);
cnd.ExecuteNonQuery();
Response.Redirect("Home.aspx");
con.Close();
}
catch (Exception ex)
{
}
telerik:RadGrid ID="RadGrid1"
runat="server" AllowMultiRowSelection="True" AllowPaging="True" DataSourceID="SqlDataSource1" GridLines="Both" PageSize="5" >
<GroupingSettings CollapseAllTooltip="Collapse all groups" />
<ClientSettings>
<Selecting AllowRowSelect="True" />
</ClientSettings>
<MasterTableView>
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:CheckBox ID="chkSelect" runat="server" Checked='<%# Eval("IsSelected") %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="Report" HeaderText="Report" ItemStyle-Width="150px" />
</telerik:GridTemplateColumn>
</Columns>
</MasterTableView>
</telerik:RadGrid>
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:AdventureWorks2014ConnectionString %>" SelectCommand="SELECT [ReportID], [Report] FROM [Report]"></asp:SqlDataSource>
<br />
To access the rows, loop through its DataItems. More about Accessing Cells and Rows
protected void Button1_Click(object sender, EventArgs e)
{
foreach (GridDataItem row in RadGrid1.Items)
{
string rowValue = row["ColumnUniqueName"].Text;
}
}
Better approach would be to create a method that takes few parameters to Update the SQL database. Once done, call it inside the ItemDataBound event of RadGrid (Differences Between ItemCreated and ItemDataBound). In this event you can access the row, its cells, get the necessary value and update the database row-by-row.
bool IsClicked = false;
protected void Button1_Click(object sender, EventArgs e)
{
IsClicked = true;
RadGrid1.Rebind();
}
protected void RadGrid1_ItemDataBound(object sender, GridItemEventArgs e)
{
if (IsClicked && e.Item is GridDataItem)
{
updateDatabase(((GridDataItem)e.Item)["ColumnUniqueName"].Text);
}
}
protected void updateDatabase(string field)
{
// update SQL
}
Related
I Have a table with 10000 records, so I want call only 15 Records at a single time using Stored procedure.
At the Next time call only next 15 Reocords and go On...
Please Help me out!!...If Possible Give Code With Example and Stored Procedure...Thank You!!!
Use paging in gridview as AllowPaging="true" then use
OnPageIndexChanging Event and give us PageSize see below example
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false" AllowPaging="true"
OnPageIndexChanging="OnPageIndexChanging" PageSize="10">
<Columns>
<asp:BoundField ItemStyle-Width="150px" DataField="Column_Name" HeaderText="Header Name" />
<asp:BoundField ItemStyle-Width="150px" DataField="Column_Name" HeaderText="Header Name" />
<asp:BoundField ItemStyle-Width="150px" DataField="Column_Name" HeaderText="Header Name" />
</Columns>
</asp:GridView>
Now bind the gridview with database on Page_Load Event
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindGrid();
}
}
private void BindGrid()
{
string conStr = #"Your connection string here";
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand("SELECT * FROM Table_Name"))
{
using (SqlDataAdapter sda = new SqlDataAdapter())
{
cmd.Connection = con;
sda.SelectCommand = cmd;
using (DataTable dt = new DataTable())
{
sda.Fill(dt);
GridView1.DataSource = dt;
GridView1.DataBind();
}
}
}
}
}
for pages use newPageIndex on OnPageIndexChanging event
protected void OnPageIndexChanging(object sender, GridViewPageEventArgs e)
{
GridView1.PageIndex = e.NewPageIndex;
BindGrid();
}
i need to create a webpage containing a grid view with combo box. condition is:- the combo box value should be inserted on my SQL db and update the db/grid view when i click save button.[i added the image of proposed design of the page]any help with the code is so much appreciated! thank you!
GridView Markup
Below I have a simple GridView ASP.Net GridView control populated from the Customers table of Northwind database. It displays 2 columns Contact Name and City of which city is editable via ASP.Net DropDownList control. The identifier column Customer Id is bind to the DataKeyNames property.
<asp:GridView ID="gvCustomers" DataKeyNames = "CustomerId" runat="server" AutoGenerateColumns = "false" OnRowEditing = "EditCustomer" OnRowDataBound = "RowDataBound" OnRowUpdating = "UpdateCustomer" OnRowCancelingEdit = "CancelEdit">
<Columns>
<asp:BoundField DataField = "ContactName" HeaderText = "Contact Name" />
<asp:TemplateField HeaderText = "City">
<ItemTemplate>
<asp:Label ID="lblCity" runat="server" Text='<%# Eval("City")%>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:Label ID="lblCity" runat="server" Text='<%# Eval("City")%>' Visible = "false"></asp:Label>
<asp:DropDownList ID = "ddlCities" runat = "server">
</asp:DropDownList>
</EditItemTemplate>
</asp:TemplateField>
<asp:CommandField ShowEditButton="True" />
</Columns>
</asp:GridView>
Binding the GridView
Below is the code to Bind the GridView control with data.
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
this.BindData();
}
}
private void BindData()
{
string query = "SELECT top 10 * FROM Customers";
SqlCommand cmd = new SqlCommand(query);
gvCustomers.DataSource = GetData(cmd);
gvCustomers.DataBind();
}
private DataTable GetData(SqlCommand cmd)
{
string strConnString = ConfigurationManager.ConnectionStrings["conString"].ConnectionString;
using (SqlConnection con = new SqlConnection(strConnString))
{
using (SqlDataAdapter sda = new SqlDataAdapter())
{
cmd.Connection = con;
sda.SelectCommand = cmd;
using (DataTable dt = new DataTable())
{
sda.Fill(dt);
return dt;
}
}
}
}
Editing the GridView Row
The below events handle the GridView Row Edit and Cancel Edit Events
C#
protected void EditCustomer(object sender, GridViewEditEventArgs e)
{
gvCustomers.EditIndex = e.NewEditIndex;
BindData();
}
protected void CancelEdit(object sender, GridViewCancelEditEventArgs e)
{
gvCustomers.EditIndex = -1;
BindData();
}
I want to bind only Table Columns to CheckBoxList and then the selected columns should be displayed in a GridView.
My code so far is:
public void BindCheckBoxList(DataSet ds)
{
int i = 0;
foreach (DataColumn dc in ds.Tables[0].Columns)
{
ListItem li = new ListItem(dc.ToString(), i.ToString());
CheckBoxList1.Items.Add(li); i++;
}
}
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false" DataKeyNames="HobbyId">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:CheckBox ID="chkSelect" runat="server" Checked='<%# Eval("IsSelected") %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="Hobby" HeaderText="Hobby" ItemStyle-Width="150px" />
</Columns>
</asp:GridView>
<br />
<asp:Button ID="btnSave" runat="server" Text="Save" OnClick="Save" />
in aspx.cs code
private void BindGrid()
{
string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand("SELECT [HobbyId], [Hobby], [IsSelected] FROM Hobbies"))
{
using (SqlDataAdapter sda = new SqlDataAdapter())
{
cmd.Connection = con;
sda.SelectCommand = cmd;
using (DataTable dt = new DataTable())
{
sda.Fill(dt);
GridView1.DataSource = dt;
GridView1.DataBind();
}
}
}
}
}
protected void mainGridView_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow &&
(e.Row.RowState == DataControlRowState.Normal ||
e.Row.RowState == DataControlRowState.Alternate))
{
if (e.Row.Cells[1].FindControl("selectCheckbox") == null)
{
CheckBox selectCheckbox = new CheckBox();
//Give id to check box whatever you like to
selectCheckbox.ID = "newSelectCheckbox";
e.Row.Cells[1].Controls.Add(selectCheckbox);
}
}
}
i think you use this code.
Here a complete example to hide GridView Columns based on a CheckBoxList.
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
//fill the datatable from the database
DataTable dt = //fill the table here...
//bind the table to the grid
GridView1.DataSource = dt;
GridView1.DataBind();
//loop all the datatable columns to fill the checkboxlist
for (int i = 0; i < dt.Columns.Count; i++)
{
CheckBoxList1.Items.Insert(i, new ListItem(dt.Columns[i].ColumnName, dt.Columns[i].ColumnName, true));
}
}
}
protected void CheckBoxList1_TextChanged(object sender, EventArgs e)
{
//loop all checkboxlist items
foreach (ListItem item in CheckBoxList1.Items)
{
if (item.Selected == true)
{
//loop all the gridview columns
for (int i = 0; i < GridView1.Columns.Count; i++)
{
//check if the names match and hide the column
if (GridView1.HeaderRow.Cells[i].Text == item.Value)
{
GridView1.Columns[i].Visible = false;
}
}
}
}
}
And on the .aspx page
<asp:CheckBoxList ID="CheckBoxList1" runat="server" OnTextChanged="CheckBoxList1_TextChanged" AutoPostBack="true"></asp:CheckBoxList>
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false">
<Columns>
<asp:BoundField DataField="field01" HeaderText="Column A" />
<asp:BoundField DataField="field02" HeaderText="Column B" />
<asp:BoundField DataField="field03" HeaderText="Column C" />
<asp:BoundField DataField="field04" HeaderText="Column D" />
<asp:BoundField DataField="field05" HeaderText="Column E" />
</Columns>
</asp:GridView>
Note that AutoGenerateColumns is set to false. If they are auto-generated the columns are not part of the GridView Columns Collection.
And of course HeaderText="xxx" must match the column names from the database that are stored in the DataTable.
I have gridview and some textbox that user can search .
when user search I updated gridview but when changed pageing I bind gridview again and I lost search result .
how can I change gridview paging without call DataBind Again?
I used this for Paging:
protected void grv_Data_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
grv_Data.PageIndex = e.NewPageIndex;
TicketDataBinding();
}
and my search method is :
protected void btn_search_Click(object sender, EventArgs e){
using (var ticket = new BLL.Ticket())
{
grv_Data.DataSource = tit.SelectList( fromDate, toDate);
grv_Data.DataBind();
}}
sorry I forgot asp.net webform and I dont know how do this ?
I've included two examples of binding data to a GridView where paging still works on filtered data. I hope it helps you.
1.You can do this completely in .ASPX:
<form id="form1" runat="server">
<asp:TextBox ID="txtEmailAddress" runat="server"></asp:TextBox>
<asp:Button runat="server" Text="Search" />
<asp:GridView ID="GridView1" runat="server" DataSourceID="sqlDS" AllowPaging="true" PageSize="5" AutoGenerateColumns="true">
<Columns>
<asp:BoundField DataField="EmailType" />
<asp:BoundField DataField="EmailAddress" />
</Columns>
</asp:GridView>
<asp:SqlDataSource ID="sqlDS"
runat="server"
ConnectionString="<%$ ConnectionStrings:conn %>"
SelectCommand="SELECT EmailType, EmailAddress FROM EmailNotifications WHERE EmailAddress LIKE #EmailAddressParam + '%'">
<SelectParameters>
<asp:ControlParameter ControlID="txtEmailAddress" DbType="String" Name="EmailAddressParam" DefaultValue="%" />
</SelectParameters>
</asp:SqlDataSource>
</form>
2.Or in code behind:
public partial class PagingAndSearchingInGridView : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
this.GetData();
}
private void GetData()
{
string emailAddress = txtEmailAddress.Text;
DataTable table = !Page.IsPostBack ? GetEmails() : GetEmails(emailAddress);
GridView1.DataSource = table;
GridView1.DataBind();
}
private DataTable GetEmails(string emailAddress = "%")
{
var table = new DataTable();
string connectionString = ConfigurationManager.ConnectionStrings["conn"].ConnectionString;
using (var connection = new SqlConnection(connectionString))
{
using (var command = new SqlCommand("SELECT EmailType, EmailAddress FROM EmailNotifications WHERE EmailAddress LIKE #EmailAddressParam + '%'", connection))
{
command.Parameters.AddWithValue("#EmailAddressParam", emailAddress);
using (var a = new SqlDataAdapter(command))
{
connection.Open();
a.Fill(table);
connection.Close();
}
}
}
return table;
}
protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
GridView1.PageIndex = e.NewPageIndex;
this.GetData();
}
}
While the pageIndex changed event, you can check whether the search button is already clicked or not. When clicking the search button you can set a hiddenfield value to 1 or something like that.
protected void grv_Data_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
grv_Data.PageIndex = e.NewPageIndex;
if(status==1) //Search button is already clicked, means the grid contains searched result
{
grv_Data.DataSource = tit.SelectList( fromDate, toDate);
}
else
{
//Search button is not clicked .. means the grid contains all records.
TicketDataBinding();
}
}
I have a gridview as below
<asp:GridView ID="gvDoctorList" runat="server" AutoGenerateColumns="False" DataSourceID="SqlDataSource1"
AllowPaging="True" AllowSorting="True"
OnSelectedIndexChanged="gvDoctorList_SelectedIndexChanged" OnRowCommand="gvDoctorList_RowCommand" OnRowDataBound="gvDoctorList_RowDataBound">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<%--<asp:CheckBox runat="server" ID="chk" OnCheckedChanged="chk_CheckedChanged" AutoPostBack="true" />--%>
<asp:Label runat="server" ID="lblPID" Visible="false" Text='<%# Eval("PatientId") %>'></asp:Label>
<asp:Button ID="btnSelect" runat="server" Text="Select" CommandArgument='<%# Eval("PatientId") %>' CommandName = "Select" />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="PatientId" HeaderText="PatientId" SortExpression="PatientId" />
<asp:BoundField DataField="firstname" HeaderText="firstname" SortExpression="firstname" />
<asp:BoundField DataField="lastname" HeaderText="lastname" SortExpression="lastname" />
<asp:BoundField DataField="sex" HeaderText="sex" SortExpression="sex" />
</Columns>
</asp:GridView>
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:MyDatabaseConnectionString %>"
SelectCommand="SELECT [PatientId],[firstname], [lastname], [sex] FROM [PatientDetails]"></asp:SqlDataSource>
<asp:Button ID="btnformatric" runat="server" Text="formatric3d" OnClick="btnformatric_Click" />
Code behind gridview rowcommand is as below
protected void gvDoctorList_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "Select")
{
int pID = Convert.ToInt32(e.CommandArgument);
Session["PatientId"] = Convert.ToString(e.CommandArgument);
//Server.Transfer("Patientstaticformatrix.aspx");
string pIDstr = Convert.ToString(Session["PatientId"]);
if (!string.IsNullOrEmpty(pIDstr))
{
int patientID = Convert.ToInt32(pID);
//string connection = System.Configuration.ConfigurationManager.ConnectionStrings["connectionString"].ConnectionString;
string sqlquery = "SELECT * FROM [MyDatabase].[dbo].[PatExam] where PId = '" + patientID + "'";
string connection = System.Configuration.ConfigurationManager.ConnectionStrings["connectionString"].ConnectionString;
using(SqlConnection conn = new SqlConnection(connection))
{
//SqlConnection conn = new SqlConnection(con);
DataSet ds;
ds = new DataSet();
SqlDataAdapter cmpatientexam;
conn.Open();
cmpatientexam = new SqlDataAdapter(sqlquery, conn);
cmpatientexam.Fill(ds, "PatientExam");
TreeNode pidnode = new TreeNode();
pidnode.Text = pIDstr;
foreach (DataRow patrow in ds.Tables["PatientExam"].Rows)
{
//TreeNode tvpatexam = new TreeNode();
//tvpatexam.Text = patrow["PId"].ToString();
//TreeView1.Nodes.Add(tvpatexam);
//for (int i = 0; i < ds.Tables["PatientExam"].Columns["PId"].Count; i++)
//if (patrow["PId"].ToString() != DBNull.Value)
//{
TreeNode childtvpatexam = new TreeNode();
childtvpatexam.Text = patrow["Exam"].ToString();
pidnode.ChildNodes.Add(childtvpatexam);
//break;
//}
//TreeView1.Nodes.Add(tvpatexam);
}
TreeView1.Nodes.Add(pidnode);
ds.Dispose();
cmpatientexam.Dispose();
conn.Close();
conn.Dispose();
}
}
}
}
Code behind the button click event is as below
protected void btnformatric_Click(object sender, EventArgs e)
{
foreach (GridViewRow row in gvDoctorList.Rows)
{
Button btn = (Button)row.FindControl("Select");
if (btn != null)
{
string pIDstr = Convert.ToString(Session["PatientId"]);
string exam = ((Button)sender).Text;
SqlCommand cmd = new SqlCommand("INSERT INTO [dbo].[PatExam]([PId],[Exam]) VALUES (#pid,#exam)", con);
if (con.State == ConnectionState.Closed)
{
con.Open();
}
try
{
cmd.Connection = con;
cmd.Parameters.AddWithValue("#pid", pIDstr);
cmd.Parameters.AddWithValue("#exam", exam);
cmd.ExecuteNonQuery();
}
catch (Exception ex)
{
Response.Write("Error Occured: " + ex.Message.ToString());
}
finally
{
con.Close();
cmd.Dispose();
}
}
}
}
I want to insert the value which is selected from gridview using select button and insert that selected value on button click event....but with the above code it is not working...
Can anyone suggest me some other idea or if possible with these code then how...can you give me the code for it....Thanks a lot
You can add a hidden field and save Gridview's rowindex in the hidden field. In btnformatric_Click you can get the row by index and get the data. The markup:
<asp:HiddenField ID="hdnRowIndex" runat="server" Value ="" />
<asp:Button ID="btnformatric" runat="server" Text="formatric3d" OnClick="btnformatric_Click" />
In code, gvDoctorList_RowCommand method:
protected void gvDoctorList_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "Select")
{
int pID = Convert.ToInt32(e.CommandArgument);
Session["PatientId"] = Convert.ToString(e.CommandArgument);
//Server.Transfer("Patientstaticformatrix.aspx");
GridViewRow gvr = (GridViewRow)(((ImageButton)e.CommandSource).NamingContainer);
hdnRowIndex.Value = gvr.RowIndex.ToString();
... ... ... ... ... ... ... ... ... ... ... ... ... ... ...
btnformatric_Click method:
protected void btnformatric_Click(object sender, EventArgs e)
{
int rowIndex = 0;
if (int.TryParse(hdnRowIndex.Value, out rowIndex))
{
//Get the row
GridViewRow row = gvDoctorList.Rows[rowIndex];
Button btn = (Button)row.FindControl("Select");
if (btn != null)
{
string pIDstr = Convert.ToString(Session["PatientId"]);
string exam = ((Button)sender).Text;
SqlCommand cmd = new SqlCommand("INSERT INTO [dbo].[PatExam]([PId],[Exam]) VALUES (#pid,#exam)", con);
if (con.State == ConnectionState.Closed)
{
con.Open();
}
try
{
cmd.Connection = con;
cmd.Parameters.AddWithValue("#pid", pIDstr);
cmd.Parameters.AddWithValue("#exam", exam);
cmd.ExecuteNonQuery();
}
catch (Exception ex)
{
Response.Write("Error Occured: " + ex.Message.ToString());
}
finally
{
con.Close();
cmd.Dispose();
}
}
}
}
I presume that you're interested in inserting a record based on the selected PatientID value from the GridView?
What you want to do is start by setting the GridView's DataKeyNames property to PatientID like so:
<asp:GridView ID="gvDoctorList" runat="server" DataKeyNames="PatientID" ...>
Then in the btnformatric_Click event handler you can get the selected PatientID value via gvDoctorList.SelectedValue, as in:
string pIDstr = gvDoctorList.SelectedValue.ToString();
Of course, before you do the above you should check to make sure that the user has selected a patient from the grid (namely, that gvDoctorList.SelectedIndex >= 0).