Need to get selected node text and value for radtreeview - c#

protected void RadTreeView1_NodeClick(object sender, RadTreeNodeEventArgs e)
{
if (e.Node.Level != 0)
{
// value of the selected child node
string text = e.Node.Value;
}
}
here i am getting text value always null...please help me
In radtree node click event i tried to get the node value
<telerik:RadTreeView ID="RadTreeView1" runat="server" Width="300px" Height="100px" Skin="Metro" OnNodeClick="RadTreeView1_NodeClick" AutoPostBack="true" OnClientNodeClicked="">
<DataBindings>
<telerik:RadTreeNodeBinding Expanded="True"></telerik:RadTreeNodeBinding>
</DataBindings>
</telerik:RadTreeView>
private void BindGrid()
{
try
{
DataView dv;
string json = class.HttpGet(url + "Services/Product.svc/ProductCategorySD1");
json = Regex.Unescape(json);
dt = (DataTable)JsonConvert.DeserializeObject(json.Trim(new Char[] { ' ', '"', '.' }), typeof(DataTable));
dv = dt.DefaultView;
grid.DataSource = dv;
grid.DataBind();
RadTreeView1.DataTextField = "ProductCategoryName";
RadTreeView1.DataFieldID = "ProductCategoryRowId";
RadTreeView1.DataFieldParentID = "ParentProductCategoryRowId";
RadTreeView1.DataSource = dt;
RadTreeView1.DataBind();
}
catch (Exception Err)
{
}
finally { }
}
treebinded perfectly..........................

You have to explicitily set the DataValueField property of your RadTreeView and then perform DataBind operation:
RadTree1.DataTextField = "MyTextColumn"
// following line is absent from supplied sample in the OP
RadTree1.DataValueField = "MyValueColumn"
RadTree1.DataFieldID = "MyID"
RadTree1.DataFieldParentID = "MyParentID"
RadTree1.DataSource = ds
RadTree1.DataBind()
In the sample code provided in the OP you are only setting DataTextField. My guess is if you do sth like:
string text = e.Node.Text;
you will successfully read the text of RadTreeNode.

Related

c# combobox autocomplete set display text and value

I need to create a combobox autocomplete which display text Name but when I click on text it gets value "ID" binding with "Name". I have already created a code but it is not working and I'm so confusing with set display text and value into combobox and autocomplete data-source binding.
private void loadAutoCompleteValues()
{
autoCompleteCombo.AutoCompleteMode = AutoCompleteMode.SuggestAppend;
autoCompleteCombo.AutoCompleteSource = AutoCompleteSource.CustomSource;
DataTable products;
con.MysqlQuery("select * from products");
products = con.QueryEx();
Dictionary<string, string> comboSource = new Dictionary<string, string>();
for (int i = 0; i < products.Rows.Count; i++)
{
DataRow dr = products.Rows[i];
comboSource.Add(dr["id"].ToString(), dr["name"].ToString());
}
autoCompleteCombo.DataSource = new BindingSource(comboSource, null);
autoCompleteCombo.DisplayMember = "Value";
autoCompleteCombo.ValueMember = "Key";
}
private void autoCompleteCombo_SelectedIndexChanged(object sender, EventArgs e)
{
string key = ((KeyValuePair<string, string>)autoCompleteCombo.SelectedItem).Key;
string value = ((KeyValuePair<string, string>)autoCompleteCombo.SelectedItem).Value;
MessageBox.Show(key + " " + value);
}
I may be incorrect here, however using your code I simply added the line autoCompleateCombo.AutoCompleteSource = AutoCompleteSource.ListItems; to your code and it worked as expected.
autoCompleateCombo.DataSource = new BindingSource(comboSource, null);
autoCompleateCombo.DisplayMember = "Value";
autoCompleateCombo.ValueMember = "Key";
autoCompleateCombo.AutoCompleteSource = AutoCompleteSource.ListItems; //<-- Added this line

Remove selected item in combobox

I want to remove a selected item in my combobox
I have here a code upon form load, I am filling list items on combobox from database.
private void LoadComboField()
{
//string test = "<ROOT><DATA FieldGroup=\"PAYMENT_VIEW4\" FieldDescription=\"PNAME\" Output=\"1\" Filter=\"1\" FieldName=\"PATIENTNAME\" DataType=\"STRING\"/><DATA FieldGroup=\"PAYMENT_VIEW4\" FieldDescription=\"MEMID\" Output=\"1\" Filter=\"1\" FieldName=\"MEMBERID\" DataType=\"STRING\"/></ROOT>";
ReadXMLData(XMLDOC, dsCombo);
// ReadXMLData(test, dsCombo);
dt = dsCombo.Tables[0];
DataView dv1 = new DataView(dsCombo.Tables[0]);
this.cmbField.Items.Clear();
this.cmbField.DataSource = dv1;
this.cmbField.DisplayMember = "FieldDescription";
this.cmbField.ValueMember = "FieldName";
}
Then I have this code on SelectedValueChanged
private void cmbField_SelectedValueChanged(object sender, EventArgs e)
{
DataGridViewRow GridRowLoc = this.dgvFilter.CurrentRow;
AddGrid(iRowIdx);
int iRowCount = this.dgvFilter.RowCount - 1;
//this.dgvFilter.CurrentRow.IsNewRow
//if (GridRowLoc.IsNewRow) continue;
// MessageBox.Show(this.dgvFilter.RowCount.ToString());
if (this.cmbField.Text != "System.Data.DataRowView")
{
this.dgvFilter.Rows[iRowIdx].Cells["ColumnFieldName"].Value = this.cmbField.Text;
this.dgvFilter.Rows[iRowIdx].Cells["FieldName"].Value = this.cmbField.SelectedValue;
if (iRowCount <= iRowIdx)
{
DataRow drow = dttable.NewRow();
drow["ColumnNames"] = this.cmbField.Text;
drow["FieldName"]= this.cmbField.SelectedValue;
drow["Alias"]=string.Empty;
drow["DataType"]=string.Empty;
drow["Outputs"]=false;
drow["SortType"]=string.Empty;
drow["SortOrder"]=string.Empty;
drow["GroupBy"]=string.Empty;
drow["Filter"]=string.Empty;
drow["Or1"]=string.Empty;
drow["Or2"]=string.Empty;
drow["Or3"]=string.Empty;
drow["Or4"]=string.Empty;
drow["Or5"]=string.Empty;
drow["Or6"]=string.Empty;
drow["Or7"]=string.Empty;
drow["Or8"]=string.Empty;
drow["Or9"]=string.Empty;
drow["Or10"]=string.Empty;
dttable.Rows.Add(drow);
}
else
{
int irow = 0;
foreach (DataRow dr in dttable.Rows)
{
if (irow == iRowIdx)
{
dr["ColumnNames"] = this.cmbField.Text;
dr["FieldName"] = this.cmbField.SelectedValue;
}
irow++;
}
}
CheckAlias(iRowIdx, this.cmbField.Text, dgvFilter);
checkcellvalue(this.cmbField.Text, iRowIdx);
CheckSorting();
if (bGroupBySelected == true)
{
this.dgvFilter.Rows[iRowIdx].Cells["GroupBy"].Value = "Group By";
}
this.dgvFilter.DataSource = dttable;
dsFilter.AcceptChanges();
this.cmbField.Visible = false;
}
// checkcellvalue(this.cmbField.Text, iRowIdx);
//MessageBox.Show(arr_Filter[0]);
CheckoutputEnable();
}
I have this code in SelectedIndexChanged
try
{
DataTable dt1 = new DataTable();
DataRowView oDataRowView = cmbField.SelectedItem as DataRowView;
string sValue = string.Empty;
if (oDataRowView != null)
{
sValue = oDataRowView.Row["FieldDescription"] as string;
}
//int count = dttable.Rows.Count - 1;
ComboBox comboBox = (ComboBox)sender;
// Save the selected employee's name, because we will remove
// the employee's name from the list.
string selectedEmployee = (string)sValue;
int count = 0;
int resultIndex = -1;
// Call the FindStringExact method to find the first
// occurrence in the list.
resultIndex = cmbField.FindStringExact(selectedEmployee);
// Remove the name as it is found, and increment the found count.
// Then call the FindStringExact method again, passing in the
// index of the current found item so the search starts there
// instead of at the beginning of the list.
while (resultIndex != -1)
{
cmbField.Items.RemoveAt(resultIndex);
count += 1;
resultIndex = cmbField.FindStringExact(selectedEmployee,
resultIndex);
}
// Update the text in Textbox1.
txtName.Text = txtName.Text + "\r\n" + selectedEmployee + ": "
+ count;
}
//}
catch (Exception ex)
{
}
But it throws an exception, say that "items collection cannot be modified when the datasource property is set." I don't know how to fix this exception error, I think that's my only problem when removing an item on the combobox.
Please do help me on this one. Thanks in advance!
Use a BindingSource for your DataSource and CurrentItemChanged to react of changed items in CBO:
this.source = new BindingSource();
this.source.DataSource = loDs.Tables[0];
this.cmbField.DataSource = this.source;
this.source.CurrentItemChanged += source_CurrentItemChanged;
Example for eventHandler:
private void source_CurrentItemChanged(object sender, EventArgs e)
{
System.Data.DataRowView view = this.source.Current as System.Data.DataRowView;
if (view != null)
{
System.Diagnostics.Debug.WriteLine(view[0].ToString());
}
}
You can remove an item from the source like this:
this.source.RemoveAt(this.source.Find("FieldName", "PATIENTNAME"));
Show Details: A Detailed Data Binding Tutorial
You can't modify the Items collection when it comes from / is bound to a DataSource. Instead you need to modify the DataSource itself.
To delete the SelectedItem from the DataSource you can try this:
DataRowView item = cmbField.SelectedItem as DataRowView;
if (item != null) item.Delete();

How to get cell value from dataTable Asp.Net

I'm creating dynamically data table bound to Grid View. Every row is populated with button. When I determine which button is clicked on the row, I want to get the current value of cell in that row modify her.
Markup:
<asp:GridView ID="GridView2" runat="server"
OnRowDataBound="GridView2_RowDataBound">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:Button ID="btnTest" runat="server"
CommandName="odzemi"
CssClass="button2"
Font-Bold="True"
Text="-"
Width="100px"
OnClick="btnTest_Click" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
Creating the row:
private void AddNewRecordRowToGrid()
{
int counter;
if (Request.Cookies["kasa"] == null)
counter = 0;
else
{
counter = int.Parse(Request.Cookies["kasa"].Value);
}
counter++;
Response.Cookies["kasa"].Value = counter.ToString();
Response.Cookies["kasa"].Expires = DateTime.Now.AddYears(2);
if (ViewState["Markici"] != null)
{
DataTable dtCurrentTable = (DataTable)ViewState["Markici"];
DataRow drCurrentRow = null;
if (dtCurrentTable.Rows.Count > 0)
{
for (int i = 1; i <= dtCurrentTable.Rows.Count; i++)
{
HttpCookie cookie = Request.Cookies["Democookie"];
drCurrentRow = dtCurrentTable.NewRow();
drCurrentRow["FirmaID"] = Request.Cookies["firma"].Value;
drCurrentRow["Godina"] = Request.Cookies["godina"].Value;
drCurrentRow["KasaID"] = Request.Cookies["kasa"].Value;
drCurrentRow["MarkicaID"] = Request.Cookies["kasa"].Value;
drCurrentRow["Datum"] = DateTime.Now;
drCurrentRow["Masa"] = Session["masa39"];
drCurrentRow["VrabotenID"] = Session["New"];
drCurrentRow["Artikal"] = Label3.Text;
drCurrentRow["Cena1"] = Label4.Text;
//this is where i need to make changes
drCurrentRow["Kolicina"] = Label5.text;
drCurrentRow["Smena"] = Session["smena1"];
drCurrentRow["VkIznos"] = Label6.Text;
drCurrentRow["VkDanok"] = Label8.Text;
drCurrentRow["SySDatum"] = DateTime.Now;
drCurrentRow["Vid"] = Label23.Text;
drCurrentRow["Edmera"] = Label10.Text;
drCurrentRow["ArtikalID"] = Label33.Text;
}
//Removing initial blank row
if (dtCurrentTable.Rows[0][0].ToString() == "")
{
dtCurrentTable.Rows[0].Delete();
dtCurrentTable.AcceptChanges();
}
//Added New Record to the DataTable
dtCurrentTable.Rows.InsertAt(drCurrentRow,0);
//storing DataTable to ViewState
ViewState["Markici"] = dtCurrentTable;
//binding Gridview with New Row
GridView2.DataSource = dtCurrentTable;
GridView2.DataBind();
}
}
}
//determine which button is clicked in data Table
//and here
protected void btnTest_Click(object sender, EventArgs e)
{
DataTable dtCurrentTable = (DataTable)ViewState["Markici"];
var clickedRow = ((Button)sender).NamingContainer as GridViewRow;
var clickedIndex = clickedRow.RowIndex;
count--;
decimal noofcount = count;
//and here i want to get current value and modify her.
dtCurrentTable.Rows[clickedIndex]["Kolicina"] = "88";
GridView2.DataSource = dtCurrentTable;
GridView2.DataBind();
}
If the only problem is that you don't know how to read the old value as noted here:
//and here i want to get current value and modify her.
dtCurrentTable.Rows[clickedIndex]["Kolicina"] = "88";
then this works:
object oldValue = dtCurrentTable.Rows[clickedIndex]["Kolicina"];
// cast/convert it to whatever it is
or (what i prefer):
string old = dtCurrentTable.Rows[clickedIndex].Field<string>("Kolicina");
int oldValue = int.Parse(old); // in case that you don't know
int newValue = oldValue + count; // just an example
dtCurrentTable.Rows[clickedIndex].SetField("Kolicina", newValue.ToString());
I'm using the Field/SetField extension methods for DataRow because it is strongly typed and even supports nullable types.
By the way, why do you store ints as strings?

Additional information: Unable to cast object of type 'System.Windows.Forms.BindingSource' to type 'System.Data.DataTable'

I'm having a weird issue with my code. I'm currently coding a filter for my datagrid.
Whenever the user clears the text field - the following error message is brought up:
Unable to cast object of type 'System.Windows.Forms.BindingSource' to
type 'System.Data.DataTable'.
This is my code so far:
private void driverNo_TextChanged(object sender, EventArgs e)
{
// if driverNo text is empty then return all rows
if (string.IsNullOrEmpty(driverNo.Text))
{
((DataTable)dataGridView1.DataSource).DefaultView.RowFilter = string.Empty;
return;
}
// if driverNo is a numerical value then view result
int temp;
if (int.TryParse(driverNo.Text, out temp))
((DataTable)dataGridView1.DataSource).DefaultView.RowFilter = "DriverNo = " + driverNo.Text;
else
MessageBox.Show("Invalid driver number.");
driverNo.Text = "";
}
The value of DataSource is a type of BindingSource, not DataTable. Basically your expectation is incorrect. It is possible the DataTable is actually backing the BindingSource.
You very likely have a BindingSource component on your WinForms design surface. You can get to the table via something like the following:
var bindingSource = this.myBindingSource;
var dt = (DataTable)bindingSource.DataSource;
You can indirectly get to it via:
var bindingSource = (BindingSource)dataGridView1.DataSource;
var dt = (DataTable)bindingSource.DataSource;
For your code it might look like this:
private void driverNo_TextChanged(object sender, EventArgs e)
{
// if driverNo text is empty then return all rows
if (string.IsNullOrEmpty(driverNo.Text))
{
var bindingSource = (BindingSource)dataGridView1.DataSource.
var table = (DataTable)bindingSource.DataSource;
table.DefaultView.RowFilter = string.Empty;
return;
}
// if driverNo is a numerical value then view result
int temp;
if (int.TryParse(driverNo.Text, out temp))
{
var bindingSource = (BindingSource)dataGridView1.DataSource.
var table = (DataTable)bindingSource.DataSource;
table.DefaultView.RowFilter = "DriverNo = " + driverNo.Text;
}
else
MessageBox.Show("Invalid driver number.");
driverNo.Text = "";
}
DataTable dt = ((DataView)gridView1.DataSource).Table;
DataView dv = (DataView)gridView1.DataSource;
`xxxBindingSource.AddNew();`
`dataGridView1.CurrentRow.Cells[0].Value = "Value Here";`
`dataGridView1.CurrentRow.Cells[1].Value = "Value here";`
`xxxBindingSource.EndEdit();`

Repeater control to aggregate data?

I have a table with doctor offices and doctors in those offices that I'm populating to a repeater control. The data coming back is not aggregated. So, if there are 2 doctors in 1 office, there are 2 rows, same office, different doctor.
Is there a way to aggregate the data so the repeater shows 1 office with all of the doctors from that office so I can avoid the duplication?
In your aspx markup:
<table><tr><th>Office</th><th>Doctors</th></tr>
<asp:repeater id="Repeater" runat="server" OnItemDataBound="NextItem" ... >
<ItemTemplate><asp:Literal id="RepeaterRow" runat="server" />
</ItemTemplate>
</asp:repeater>
<asp:Literal id="LastRow" runat="server" />
</table>
In your code behind:
public class Office
{
public string OfficeName {get;set;};
List<string> _doctors = new List<string>();
public List<string> Doctors {get{ return _doctors; } };
void Clear()
{
OfficeName = "";
_doctors.Clear();
}
public override string ToString()
{
StringBuilder result = new StringBuilder("<tr>");
result.AppendFormat("<td>{0}</td>", OfficeName);
string delimiter = "";
result.Append("<td>");
foreach(string doctor in Doctors)
{
result.Append(doctor).Append(delimiter);
delimiter = "<br/>";
}
result.Append("</td></tr>");
return result.ToString();
}
}
.
private string CurOffice = "";
private Office CurRecord = new Office();
void NextItem(object sender, RepeaterItemEventArgs e)
{
if (e.Item.ItemType != ListItemType.Item && e.Item.ItemType != ListItemType.AlternatingItem) return;
Literal repeaterRow = e.Item.FindControl("RepeaterRow") as Literal;
if (repeaterRow == null) return;
DataRow row = ((DataRowView)e.Item.DataItem).Row;
if ( CurOffice != (string)row["Office"] )
{
repeaterRow.Text = CurRecord.ToString();
repeaterRow.Visible = true;
CurRecord.Clear();
CurOffice = row["Office"];
CurRecord.Office = CurOffice;
}
else
e.Item.Visible = false;
CurRecord.Doctors.Add((string)row["doctor"]);
}
void Page_PreRender(object sender, EventArgs e)
{
LastRow.Text = CurRecord.ToString();
}
I think you'd be best doing the aggregation in the database.
I was considering that but thought there might be a fancier way to do it.
If aggregating in the db, pass a delimeted column and parse it during databinding?
Use the SQL coalesce function
As from SQLTeam.com:
DECLARE #EmployeeList varchar(100)
SELECT #EmployeeList = COALESCE(#EmployeeList + ', ', '') +
CAST(Emp_UniqueID AS varchar(5))
FROM SalesCallsEmployees
WHERE SalCal_UniqueID = 1
This will create a comma delimeted list of employees. You can do this for doctors too

Categories

Resources