In my webpage, there is a RadComboBox outside the RadGrid and a Dropdown inside RadGrid.
Data inside Dropdown is bind based on RadComboBox item selection.
Ex: If from RadComboBox, item "Company" is selected, then data inside Dropdown will be related to "Company" (i.e, Company1, Company2,company3, etc)
HTML code:
<telerik:RadComboBox ID="ddlCompany" runat="server" Height="200" Width="240"
DropDownWidth="310" EmptyMessage="- Select Product -" HighlightTemplatedItems="true" CausesValidation="false" Filter="StartsWith" AppendDataBoundItems="true" AllowCustomText="true" AutoPostBack="true" DataTextField="Title" DataValueField="Code" OnSelectedIndexChanged="ddlCompany_SelectedIndexChanged">
</telerik:RadComboBox>
<telerik:RadGrid ID="RGGSTAcCode" runat="server">
<Columns>
<telerik:GridEditCommandColumn></telerik:GridEditCommandColumn>
<telerik:GridTemplateColumn UniqueName="AccountCode" HeaderText="Account Code">
<ItemTemplate>
<asp:Label ID="lblAcCode" Text='<%# Eval("AccountCode") %>' runat="server"></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:DropDownList ID="ddlAcCode" DataTextField="AccountDescription" DataValueField="AccountCodeID" runat="server"/>
</EditItemTemplate>
</telerik:GridTemplateColumn>
</Columns>
C# Code:
public DataSet GetCompanyNames()
{
SqlConnection con = new SqlConnection(strcon);
SqlCommand cmd = new SqlCommand("General.usp_tbl_BuyerCode_Query", con);
cmd.CommandType = CommandType.StoredProcedure;
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
try
{
con.Open();
da.Fill(ds);
con.Close();
}
catch (Exception ex)
{
}
return ds;
}
protected void BindComapnyDL()
{
ddlCompany.DataTextField = "Title";
ddlCompany.DataValueField = "Code";
ddlCompany.DataSource = GetCompanyNames();
ddlCompany.DataBind();
Session["Comp"] = ddlCompany.SelectedValue.ToString();
}
protected void ddlCompany_SelectedIndexChanged(object sender, RadComboBoxSelectedIndexChangedEventArgs e)
{
if (ddlCompany.SelectedItem != null)
{
SqlConnection con = new SqlConnection(strcon);
SqlDataAdapter adapter = new SqlDataAdapter();
adapter.SelectCommand = new SqlCommand("SELECT [AccountCodeID],[AccountCode]+' - '+[AccountDescription] as[AccountDescription] FROM [Sunway_AP].[General].[tbl_AccountCode] (NOLOCK) Where [CompanyCode] = '" + Session["Comp"] + "' order by [AccountCode]+' - '+[AccountDescription]", con);
con.Open();
DataTable dt = new DataTable();
try
{
adapter.Fill(dt);
}
finally
{
con.Close();
}
DropDownList list = RGGSTAcCode.FindControl("ddlAcCode") as DropDownList;
list.DataTextField = "AccountDescription";
list.DataValueField = "AccountCodeID";
list.DataSource = dt;
list.DataBind();
}
else
{
Response.Write("Please select Company first");
}
}
Now, when I try to change the company using "ddlCompany_SelectedIndexChanged" event,
I get below error:
System.NullReferenceException: Object reference not set to an instance of an object.
at line :
list.DataTextField = "AccountDescription";
Please suggest what is wrong in my code. Thanks in advance
This line contains error dropdown is not properly find
DropDownList list = RGGSTAcCode.FindControl("ddlAcCode") as DropDownList;
Where did You placed Dropdown inside any control..??
visite this link http://docs.telerik.com/devtools/aspnet-ajax/controls/grid/how-to/operations-with-ms-dropdownlist-in-edititemtemplate-of-gridtemplatecolumn
try this
foreach (GridDataItem item in RGGSTAcCode.EditItems)
{
DropDownList list = item.FindControl("ddlAcCode") as DropDownList;
//Now we can do stuff with the "list"
}
Keep in mind that the row needs to be in Edit Mode to find controls in its EditItemTemplate.
Related
So I want to make my dropdownlist to have always the same index selected, for example I have a gridview and I have a pager on it, if I change the page the index I had in my dropdownlist resets and I can give other example, I have a search textbox in my page and if I search something on it when I press enter the dropdownlist resets once again. How can I make my dropdownlist to have always the same selected index?
asp.net
<asp:GridView ID="MyGrid" runat="server"
DataKeyNames="No_" AutoGenerateColumns="false" Style="color: Black; border-collapse: collapse; margin-right: auto; display: table; text-align: center;" OnPageIndexChanging="MyGrid_PageIndexChanging" OnRowDataBound="MyGrid_RowDataBound" AllowPaging="True" OnPageIndexChanged="MyGrid_PageIndexChanged" PageSize="10" AllowCustomPaging="False">
<Columns>
<asp:BoundField DataField="No_" HeaderText="No_Encomenda" />
<asp:TemplateField HeaderText="Select">
<ItemTemplate>
<asp:CheckBox ID="CheckBox1" runat="server" OnCheckedChanged="CheckBox1_CheckedChanged" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
<PagerSettings Mode="NumericFirstLast" PageButtonCount="4" FirstPageText="First" LastPageText="Last" />
<PagerStyle CssClass="gridview" HorizontalAlign="Center" VerticalAlign="Middle" />
</asp:GridView>
cs
SqlConnection con = new SqlConnection(WebConfigurationManager.ConnectionStrings["constring"].ConnectionString);
List<string> MySelected;
protected void Page_Load(object sender, EventArgs e)
{
ButtonBack.Visible = false;
//GridView1.Visible = false;
con.Open();
SqlCommand cmd = new SqlCommand("Select bl from booking", con);
SqlDataReader sdr = cmd.ExecuteReader();
DropDownList1.Items.Clear();
DropDownList1.Items.Add("-");
if(IsPostBack == false)
{
while (sdr.Read())
{
DropDownList1.Items.Add(sdr.GetValue(0).ToString());
}
}
if (IsPostBack == false)
{
MySelected = new List<string>();
LoadGrid();
ViewState["MySelected"] = MySelected;
}
else
{
MySelected = (List<string>)ViewState["MySelected"];
}
string user = Convert.ToString(Session["user"]);
username.Text = user;
if (Session["user"] == null || Session["login"] == null)
{
Response.Redirect("Login.aspx", false);
}
if (!Page.IsPostBack)
{
refreshdata();
refreshdata();
}
con.Close();
}
public void LoadGrid()
{
SqlCommand cmd = new SqlCommand("select DISTINCT No_ from [EncomendaTEMP]", con);
{
DataTable rst = new DataTable();
rst.Load(cmd.ExecuteReader());
MyGrid.DataSource = rst;
MyGrid.DataBind();
}
}
public void refreshdata()
{
SqlCommand cmd = new SqlCommand("select DISTINCT No_ from [EncomendaTEMP]", con);
{
DataTable rst = new DataTable();
rst.Load(cmd.ExecuteReader());
MyGrid.DataSource = rst;
MyGrid.DataBind();
}
}
In Page_Load code, I see that you are loading data in dropdownlist. When the page is submitted, Page_Load will execute and it will reload the data in the dropdown list. That's why selection goes off.
You should load the data in the dropdown list only during first load of the page. As you are doing with LoadGrid(). During post back the data of the dropdown and selection will be maintained if you don't reload them.
So I suggest following code change for loading data in dropdown list.
if(!IsPostBack)
{
SqlCommand cmd = new SqlCommand("Select bl from booking", con);
SqlDataReader sdr = cmd.ExecuteReader();
DropDownList1.Items.Clear();
DropDownList1.Items.Add("-");
while (sdr.Read())
{
DropDownList1.Items.Add(sdr.GetValue(0).ToString());
}
MySelected = new List<string>();
LoadGrid();
ViewState["MySelected"] = MySelected;
}
else
{
MySelected = (List<string>)ViewState["MySelected"];
}
I hope this will help you solve your problem.
All I want to do is when A user clicks on "See more" button on gridview, He will get all the columns of the row button clicked on detailView1.. But I dont know where Im going wrong. Im working on C# asp.net
Can anyone help? Thanks in advance.
protected void Page_Load(object sender, EventArgs e)
{
var conString = ConfigurationManager.ConnectionStrings["CONSTRING"].ConnectionString;
SqlConnection con = new SqlConnection(conString);
DetailsView1.Visible = false;
SqlCommand cmd1 = new SqlCommand("SELECT cars.carid, cars.make, cars.model, cars.condition, cars.amount, img.img FROM cars INNER JOIN img ON cars.carid = img.carid ", con);
SqlDataAdapter sda1 = new SqlDataAdapter(cmd1);
DataTable dt = new DataTable();
sda1.Fill(dt);
GridView1.DataSource = dt;
GridView1.DataBind();
}
protected void Button2_Clicked(object sender, EventArgs e)
{
var conString = ConfigurationManager.ConnectionStrings["CONSTRING"].ConnectionString;
SqlConnection con = new SqlConnection(conString);
foreach (GridViewRow row in this.GridView1.Rows)
{
Label lblshow = (Label)GridView1.Rows[row.RowIndex].FindControl("carid");
SqlCommand cmd1 = new SqlCommand("Select * from cars where carid='" + lblshow.Text + "'", con);
SqlDataAdapter sda1 = new SqlDataAdapter(cmd1);
DataTable dt = new DataTable();
sda1.Fill(dt);
DetailsView1.DataSource = dt;
DetailsView1.DataBind();
}
}
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="True" Width="1000px" AllowPaging="True" PageSize="8" CssClass="Grid" AlternatingRowStyle-CssClass="alt" PagerStyle-CssClass="pgr">
<AlternatingRowStyle CssClass="alt"></AlternatingRowStyle><PagerStyle CssClass="pgr"></PagerStyle>
<Columns>
<asp:TemplateField>
<HeaderTemplate>Select</HeaderTemplate>
<ItemTemplate>
<asp:Button runat="server" Text="See more" OnClick="Button2_Clicked" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<HeaderTemplate>Image</HeaderTemplate>
<ItemTemplate>
<img src='data:image/jpg;base64,<%# Eval("img") != System.DBNull.Value ? Convert.ToBase64String((byte[])Eval("img")) : string.Empty %>' alt="image" height="100" width="150"/>
</ItemTemplate>
</asp:TemplateField>
</Columns>
IsPostback on the page load event. Hope your problem get resolved.
My code of gridview on aspx page:
<asp:TemplateField HeaderText="Payments">
<ItemTemplate>
<asp:Label ID="Label31" runat="server" Text='<% #Eval("Payments_Status") %>'>
</asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:DropDownList ID="ddltype" runat="server" CssClass="form-control" AutoPostBack="false">
<asp:ListItem Value="0" Enabled="false">Select Status</asp:ListItem>
<asp:ListItem Value="Pending">Pending</asp:ListItem>
<asp:ListItem Value="Paid">Paid</asp:ListItem>
</asp:DropDownList>
</EditItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
If the value is "Pending" in the database the dropdown should show as "Pending". Same Like for Paid .
How to fill dropdown inside a gridview select selectedValue in PageLoad(Link to screen shot)
protected void RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow && gvCustomers.EditIndex == e.Row.RowIndex)
{
DropDownList ddltype = (DropDownList)e.Row.FindControl("ddltype");
string query = "select distinct paymenttype from paymenttypes";
SqlCommand cmd = new SqlCommand(query);
ddltype.DataSource = GetData(cmd);
ddltype.DataTextField = "type";
ddltype.DataValueField = "type";
ddltype.DataBind();
ddltype.Items.FindByValue((e.Row.FindControl("Label31") as Label).Text).Selected = true;
}
}
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;
}
}
}
}
I am using asp DropDownList inside RadGrid, and trying to Add and Update the DropDownList item inside Database table.
Below is the HTML code for DropDownList inside RadGrid's EditItemTemplate:
<telerik:GridTemplateColumn UniqueName="AccountCode" HeaderText="Account Code">
<ItemTemplate>
<asp:Label ID="lblAcCode" runat="server" Text='<%# Eval("AccountCode")%>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:Label ID="lblAcCode2" runat="server" Text='<%# Eval("AccountCode") + " - " + Eval("AccountDescription")%>'></asp:Label>
<asp:DropDownList ID="ddlAcCode" DataTextField="AccountDescription" DataValueField="AccountCodeID" runat="server"/>
</EditItemTemplate>
</telerik:GridTemplateColumn>
C# Code:
public DataTable GetAccCode(string CompanyCode)
{
SqlConnection con = new SqlConnection(strcon);
SqlCommand cmd = new SqlCommand("[Invoice].[usp_tbl_AccountCode_DL_Test]", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#CompanyCode", CompanyCode);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
try
{
con.Open();
da.Fill(dt);
con.Close();
}
catch (Exception ex)
{
}
return dt;
}
protected void RGGSTAcCode_ItemDataBound(object sender, GridItemEventArgs e)
{
if (e.Item is GridEditableItem && e.Item.IsInEditMode)
{
//bind dropdwon while "Add"
string CompanyCode = ddlCompany.SelectedValue.ToString();
GridEditableItem item = (GridEditableItem)e.Item;
DropDownList ddl = (DropDownList)item.FindControl("ddlAcCode");
ddl.DataSource = GetAccCode(CompanyCode);
ddl.DataTextField = "AccountDescription";
ddl.DataValueField = "AccountCodeID";
ddl.DataBind();
ddl.Items.Insert(0, "- Select -");
//Select particular dropdown value while "Edit"
string accCodeID = item.GetDataKeyValue("AccountCodeID").ToString();
Label lblAcCode2 = item.FindControl("lblAcCode") as Label;
//if (!string.IsNullOrEmpty(lblAcCode2.Text))
//{
ddl.SelectedValue = lblAcCode2.Text;
//}
//string SelectedVal = ddl.SelectedValue;
if (!string.IsNullOrEmpty(lblAcCode2.Text))
{
SqlConnection con = new SqlConnection(strcon);
con.Open();
SqlDataAdapter adapter = new SqlDataAdapter();
adapter.SelectCommand = new SqlCommand("SELECT [AccountCode]+' - '+[AccountDescription] as [AccountDescription] FROM [Sunway_AP].[Invoice].[tbl_AccountCodeTest] where AccountCodeID='" + accCodeID + "' ", con);
DataTable dt = new DataTable();
try
{
adapter.Fill(dt);
}
finally
{
con.Close();
}
ddl.SelectedValue = dt.ToString();
string SelectedVal = ddl.SelectedValue;
}
}
}
This is the Stored Procedure:
ALTER PROCEDURE [Invoice].[usp_tbl_AccountCode_DL_Test]
#CompanyCode nvarchar(50)
AS
BEGIN
SET NOCOUNT ON;
SELECT [AccountCodeID] ,[AccountCode]+' - '+[AccountDescription] as [AccountDescription]
FROM [Sunway_AP].[General].[tbl_AccountCode] (NOLOCK)
Where [CompanyCode] = #CompanyCode
order by [AccountCode]+' - '+[AccountDescription]
END
My problem is: I am unable to fetch the "DropDownList's" selected value for a particular Id (particular row of RadGrid), while Edit.
Everytime when I try to set the Selected Value of DropdownList from code behind, it shows me 1st item '- Select -' inside the selected value.
Please reply what is wrong in my code.
I am very new in Telerik. Thanks in advance.
Modified my posted code as below:
protected void RGGSTAcCode_ItemDataBound(object sender, GridItemEventArgs e)
{
if (e.Item is GridEditableItem && e.Item.IsInEditMode)
{
//bind dropdwon while "Add"
string CompanyCode = ddlCompany.SelectedValue.ToString();
GridEditableItem item = (GridEditableItem)e.Item;
DropDownList ddl = (DropDownList)item.FindControl("ddlAcCode");
ddl.DataSource = GetAccCode(CompanyCode);
ddl.DataTextField="*your text field*";
ddl.DataValueField="*your Value field*";
ddl.DataBind();
ddl.Items.Insert(0, "- Select -");
Label lblAcCode2 = item.FindControl("lblAcCode2") as Label;
if (!string.IsNullOrEmpty(lblAcCode2.Text))
{
ddl.SelectedItem.Text = lblAcCode2.Text;
ddl.SelectedValue = lblAcCode2.Text;
}
}
}
<telerik:GridTemplateColumn UniqueName="AccountCode" HeaderText="Account Code">
<ItemTemplate>
<asp:Label ID="lblAcCode" runat="server" Text='<%# Eval("AccountCode")%>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:Label ID="lblAcCode2" runat="server" Text='<%# Eval("AccountCode") + " - " + Eval("AccountDescription")%>' Visible="false"></asp:Label>
<asp:DropDownList ID="ddlAcCode" DataTextField="AccountDescription" DataValueField="AccountCodeID" runat="server"/>
</EditItemTemplate>
</telerik:GridTemplateColumn>
Hope this helps...
All the best...
I have an access DB (.mdb) named: Programs, with one table named: Data. By using the DataGridView I present the data from the table Data. I want to delete a row from the DataGridView and from the DB during runtime. Does anyone know how to do that (using C#)?
Another question I have is, who can i run queries on my DB?
thanks!
Very simple.
I suppose in your datagrid you have a check box by choosing which you will be able to choose the rows that you want to delete. And assuming you have a submit button, so after choosing the rows click on the submit button. In the button's click event call the Delete query say delete from tblname where id = #id [#id is the id that will be passed from your grid]
After that just populate the grid e.g. select * from tblname
e.g.
Aspx code
<asp:GridView runat="server" ID="gvTest" Width="100%" AutoGenerateColumns="false">
<Columns>
<asp:TemplateField HeaderText="Select" ItemStyle-HorizontalAlign="Center" ItemStyle-Width="5%">
<ItemTemplate>
<asp:CheckBox ID="chkDel" runat="server" />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField HeaderText="RegID" DataField="RegID" ItemStyle-Width="10%">
<ItemStyle HorizontalAlign="Left"/>
</asp:BoundField>
<asp:TemplateField HeaderText="Name" ItemStyle-Width="22%" ItemStyle-HorizontalAlign="Left">
<ItemTemplate>
<asp:Label ID="lblName" runat="server" Width="100%" Text= '<%# DataBinder.Eval(Container.DataItem, "UserName")%>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<br>
<asp:Button runat="server" ID="btnSubmit" Text="Submit" OnClick="btnSubmit_Click"></asp:Button>
Submit button cilck event's code
protected void btnSubmit_Click(object sender, EventArgs e)
{
for (int count = 0; count < gvTest.Rows.Count; count++ )
{
CheckBox chkSelect = (CheckBox)gvTest.Rows[count].FindControl("chkDel");
if (chkSelect != null)
{
if (chkSelect.Checked == true)
{
//Receiveing RegID from the GridView
int RegID = Int32.Parse((gvTest.Rows[count].Cells[1].Text).ToString());
object result = DeleteRecord(RegID); //DeleteRecord Function will delete the record
}
}
}
PopulateGrid(); //PopulateGrid Function will again populate the grid
}
public void DeleteRecord(int RegId)
{
string connectionPath = "Data Source=<your data source>;Initial Catalog=<db name>;Integrated Security=True;userid='test';pwd='test'";
string command = "";
SqlConnection connection = new SqlConnection(#connectionPath);
command = "delete from tblname where id = " + RegId
try
{
connection.Open();
SqlCommand cmd = new SqlCommand(command, connection);
cmd.ExecuteNonQuery();
}
catch (SqlException sqlExcep) {}
finally
{
connection.Close();
}
}
public void PopulateGrid()
{
DataTable dt = new DataTable();
dt = GetRecord();
if(dt !=null && dt.rows.count>0)
{
gvTest.DataSource = dt;
gvTest.DataBind();
}
}
public DataTable GetRecord()
{
string connectionPath = "Data Source=<your data source>;Initial Catalog=<db name>;Integrated Security=True;userid='test';pwd='test'";
string command = "";
SqlDataAdapter adapter = new SqlDataAdapter();
SqlConnection connection = new SqlConnection(#connectionPath);
command = "Select * from tblname" ;
connection.Open();
SqlCommand sqlCom = new SqlCommand(command, connection);
adapter.SelectCommand = sqlCom;
DataTable table = new DataTable();
adapter.Fill(table);
return table;
}
Hope this makes sense.