Get SQL data via listbox - sql

Ok, so what I am trying to do is click one item in a listbox that i have, that listbox gets data from the sql database depending on that the user types into the textbox.
Now when I click that item in the first listbox, I need more info related to that item to show up in the 2nd list box.
When the user enters a name in the textbox, the first 10 in sql show up, now that I have that, I need to click on one of the items and get the 'task' of that client in the next listbox. Task is MATTERS in the database.
I am pretty sure that my code is correct, I get no errors but nothing shows up in the list box.
Here is my code:
private void listBox1_SelectedValueChanged(object sender, EventArgs e)
{
string item = listBox1.SelectedItem.ToString();
if (listBox1.ContainsFocus)
{
if (item == "")
{
}
else
{
var con2 = Conn.ConnString();
using (SqlConnection myConnection2 = new SqlConnection(con2))
{
string oString2 = "select CLIENTMATTERS.MATTER, CLIENTMATTERS.DESCRIPTION from CLIENTMATTERS join CLIENTCODES on CLIENTMATTERS.CLIENT = CLIENTCODES.CLIENT Where CLIENTCODES.DESCRIPTION = '#code1'";
SqlCommand oCmd = new SqlCommand(oString2, myConnection2);
oCmd.Parameters.AddWithValue("#code1", item);
myConnection2.Open();
oCmd.Connection.Open();
List<string> codelist2 = new List<string>();
using (SqlDataReader oReader2 = oCmd.ExecuteReader())
{
if (oReader2.HasRows)
{
string value = string.Empty;
while (oReader2.Read())
{
codelist2.Add(oReader2["MATTER"].ToString());
}
}
}
this.listBox2.DataSource = codelist2;
}
}
}
}

You need to use BindingList<> instead of List<>.
The List<> doesn't implement the ListChanged event, so the ListBox doesn't get notified when the datasource changes.
In your example it would look like this:
BindingList<string> codelist2 = new BindingList<string>();
For further information take a look at
BindingList on MSDN.

Related

XAML forms have second picker sorted based on selection in first picker

I have 2 dropdowns (pickers) on a XAML form. The first is an ObservabelCollection of Territories. The second is an ObservableCollection of type Tracks. When the form loads my ViewModel loads both collections and each collection is bound to a picker. I want to filter and display only those tracks that are associated with the selected territory in the second picker.
FYI-the second picker is disabled until a selection is made in the first. Actually I don't require that the second picker's data source be set as the form loads, unless the solution requires it. The selection in the first picker will be the key to filter the data for the second.
I have tried to handle the filtering in the Territory picker's SelectedIndexChanged event but my ObservableCollection 'tracks' is not exposed here.
private void territoryPicker_SelectedIndexChanged(object sender, EventArgs e)
{
var picker = (Picker)sender;
string territory = picker.SelectedItem.ToString();
Tracks _track = tracks.Where(X => X.Territory = territory);<<<==== Does not work
trackPicker.ItemsSource = _track.Track;<<<==== Does not work
trackPicker.IsEnabled = true;
}
I've also tried to not build the Tracks OC until after the Territory is selected like this:
private void territoryPicker_SelectedIndexChanged(object sender, EventArgs e)
{
var picker = (Picker)sender;
string territory = picker.SelectedItem.ToString();
TrackViewModel vm = new TrackViewModel();
var _tracks = (Tracks)vm.Tracks; <<<<<==== This does not work
trackPicker.IsEnabled = true;
}
The ViewModel runs and the tracks are loaded via the API but when it returns here Tracks is empty.
I'm open to a reasonable solution (not 3rd party controls/packages) that will accomplish this task . Thanks
I figured it out by stumbling over the answer while researching another issue. I have been referencing my viewmodel in the {content].xaml page like this.
<ContentPage.BindingContext>
<vm:TrackViewModel />
</ContentPage.BindingContext>
When doing so the resources of that vm were not available in the code behind. But when I reference the VM in the page constructor Like this:
public partial class RequestmyTracks : ContentPage
{
TrackViewModel trackviewmodel = new TrackViewModel();
And then bind it here:
public RequestmyTracks()
{
InitializeComponent();
BindingContext = trackviewmodel;
}
The trackviewmodel is accessible in the SelectedIndexChanged event and everything else was really straight forward, Which looks like this:
private void territoryPicker_SelectedIndexChanged(object sender, EventArgs e)
{
var picker = (Picker)sender;
string territory = picker.SelectedItem.ToString();
ObservableCollection<Tracks> dah = (ObservableCollection<Tracks>)trackviewmodel.Tracks;
List<string> trackNames = new List<string>();
foreach (var track in dah)
{
if (track.Territory == territory)
trackNames.Add(track.Track);
}
trackPicker.ItemsSource = trackNames;
if(trackNames.Count ==1)
trackPicker.SelectedIndex = 0;
trackPicker.IsEnabled = true;
}
Thanks for the help

Excel report unauthorized error link

I am making excel report of my SQL server table records. In Asp page grid view I am fetching required data then this data is downloaded in excel. one column has hyperlink value & I need this hyperlink should only work in Asp page Grid view but after download, it should redirect to a new page where Unauthorized access error will be shown. I am not getting how to show unauthorized error link in excel file hyperlink click.
Here is my code
protected void LnkBtnViewImage_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(cs);
LinkButton lnkbtimage = sender as LinkButton;
GridViewRow gvrowreport = lnkbtimage.NamingContainer as GridViewRow;
//int Exhid = Convert.ToInt32(gvrowreport.Cells[1].Text);
string Exhid = ((HiddenField)gvrowreport.Cells[0].FindControl("HiddenField1")).Value;
SqlCommand cmd = new SqlCommand("select ImageName,ImageData from CompanyImage where Edition_Id='" + Session["Edition_ID"].ToString() + "' and Exhibitor_ID=#Exhibitor_ID ", con);
cmd.Parameters.AddWithValue("#Exhibitor_ID", Exhid);
//Select Statement con
if (con.State == ConnectionState.Closed)
{
con.Open();
}
SqlDataReader dr = cmd.ExecuteReader();
if (dr!=null)
{
dr.Read();
LinkButton lnkbtn = sender as LinkButton;
GridViewRow gvrow = lnkbtn.NamingContainer as GridViewRow;
//string filePath = GridViewLogo.DataKeys[gvrow.RowIndex].Value.ToString();
//if (!Convert.IsDBNull(dr["ImageData"]))
//{
Response.ContentType = "application/vnd.ms-jpg";
//to open file prompt Box open or Save file
Response.AddHeader("content-disposition", "attachment;filename=" + dr["ImageName"].ToString());
Response.Charset = "";
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.BinaryWrite((byte[])dr["ImageData"]);
Response.End();
//}
//else
//{
// //lblhid.Text = "Image is not uploaded here !!";
// //lblhid.ForeColor = Color.Green;
// //lblhid.Visible = true;
// //// lblhexcelerror.Visible = false;
// //gvrow.Visible = false;
//}
}
else
{
//LinkButton lnkbtn = sender as LinkButton;
//GridViewRow gvrow = lnkbtn.NamingContainer as GridViewRow;
//gvrow.Visible = false;
}
con.Close();
With a few specific exceptions (e.g. forms with CSRF tokens) it's usually the case that when you click on a link the server doesn't care how you got there, it receives the request and serves the requested page or resource. It doesn't really know whether the link was contained within an Excel file, or another HTML document, an email etc. That's one of the clever things about hyperlinks, in fact.
Even if what you were suggesting was feasible, there would be nothing to stop a user from copying and pasting it into their browser and accessing it from there.
If you don't want this link to work from your Excel document, and/or you don't want users to be given the link, the simplest thing would be not to include it in the document in the first place.
Also if it's the case that this link is being given to users who shouldn't have access to whatever is shown the link, then simply not giving them the link ("security by obscurity") is not really adequate protection. If that's the situation then you need to think about how access to that link is authorised, no matter where the user acquired the knowledge of it.
use trim in code of reports.
In trim you have to remove "mailto:" while exporting it to the excel

How do I retrieve a particular piece of metadata of a selected List Item in Visual Studio (Sharepoint)?

I'm doing up a web part using visual studio for my sharepoint site and I require part of it to retrieve documents which are related to the selected one.
Each document which I've created on the sharepoint site for testing purposes has its own metadata and I wish to retrieve the documents which have a particular piece of metadata (say, 'file name' or 'written by' etc.)
hence in the method which I've coded for this particular function, I've managed to retrieve the metadata collectively into a hashtable (or so I think i have) but I can't seem to extract a single piece of metadata out of it.
protected void displayFileNames(object sender, EventArgs e) {
String selectedDocLib = TypeOfDocument.SelectedValue;
objCurrentWeb = SPContext.Current.Web;
SPListCollection objDocLibList = objCurrentWeb.GetListsOfType(SPBaseType.DocumentLibrary);
String tempStr = "";
SPList tempDocLib;
Hashtable hT = new Hashtable();
foreach (SPList docLibList in objDocLibList) {
tempStr = docLibList.Title;
if (tempStr.Equals(selectedDocLib)) {
tempDocLib = objDocLibList.TryGetList(selectedDocLib);
foreach (SPListItem objTempDocLibItem in tempDocLib.Items) {
hT = objTempDocLibItem.Properties;
int isOriginal = hT.GetHashCode();
ListBox1.Items.Add(objTempDocLibItem.Name);
}
}
}
}
Please help me out here!!
Thank you!!!
Hailey

Binding multiple textbox controls to database rows

I´m trying to store some parameters for my application on a database table. The table contains multiple rows which contains a Key -> Value relationships. On my windows forms program (written in C#) I have multiple controls that should allow the user to interact with the stored configuration on the database.
For example, my database table looks like the following:
id option_name option_value
1 serial_port_baudrate 9600
2 serial_port_stopbits one
On my form I have controls that allow to change those values. After some research I've obtained the expected results using the bindingSource class and the filter property. But I have to create a bindingSource object for each textbox using the visual editor. Can you please help me to archieve this with multiple textboxes and controls without using the visual editor?
I dont know if it´s possible but I would like to code a solution where I could just name the textboxes on my form with the same name of the Key that holds the value in the database and then they would get the correct values when the application runs. I would appreciate any information or hints you could provide.
Thanks in advance.
Well, you could name all the text boxes the same as the database fields, then loop through all the textbox controls on the form. Use the name of the form as a parameter as in the below code:
DataTable table = new DataTable();
//Populate datatable
TextBox txt = new TextBox();
foreach(DataRow row in table.Rows)
{
String controlID = row["option_name"].ToString();
txt.ID = controlID;
(new TextBox()).ID = controlID;
txt.Text = table.Rows[table.Rows.IndexOf(row)][controlID].ToString();
}
This is what I use for my Options table:
void loadOptions(Control parent)
{
foreach (Control c in parent.Controls)
{
DataRow[] res = options.Select("option='" + c.Name + "'");
if (c is GroupBox)
{
loadOptions(c);
continue;
}
if (res.Length < 1) continue;
DataRow row = (DataRow)res.GetValue(0);
String value = row["value"].ToString();
if (c is TextBox)
{
c.Text = value;
}
else if (c is CheckBox)
{
((CheckBox)c).Checked = Convert.ToBoolean(value);
}
else if (c is NumericUpDown)
{
((NumericUpDown)c).Value = int.Parse(value);
}
}
}
I'm not sure if this is the best solution, but it works. I'm always looking for a better way if anybody has one.

How do I make the "change order" button appear in SharePoint 2010?

How do I make the "change order" button appear in SharePoint 2010?
I have followed a guide that allowed me to add OrderedList="TRUE" to my list template. This makes it possible to select "Allow users to order items in this view" for my view. But the change order button is still missing. Any idears on what I am missing?
I am using SharePoint 2010 and the guide is from 2006, so that might explain why it doesn't just work.
The guide from tech-archive.net.
Not sure if you tried this already, but in SP 2007 after you deploy your list adding the OrderedList=TRUE attribute, you still need to modify the view and under sorting you'll see a new option "Allow user to sort items in this view". The "Change Order" button doesn't appear until you set that option to "Yes".
I created a little console app to help me set the OrderedList attribute.
class Program {
public static SPSite GetAdminSPSite() {
SPSite spsite = null;
SPSecurity.RunWithElevatedPrivileges(delegate() {
spsite = new SPSite("http://sharepointdev");
});
return spsite;
}
static void Main(string[] args) {
if (args.Length != 2) {
Console.WriteLine("Missing sitename parameter and the list name.");
return;
}
string sitename = args[0];
string listname = args[1];
using (SPSite site = GetAdminSPSite()) {
using (SPWeb web = site.OpenWeb("ClientSites/" + sitename)) {
SPList list = web.Lists[listname];
list.Ordered = true;
list.Update();
}
}
}
}
Once that is run then you need to modify the view as #Jeff Smith says.