How to filter datagridview using text inputted from a rich text box? - c#-3.0

I have a datagridview that I want to display a data from a database. But I don't want it to display all of the data. I want it to display the data for a specific ID only. Meaning if the user enters 3 ID, it will display the info for that 3 ID. Hence I want to use a rich text box as a filter so that the user can enter multiple ID for each line in the rich text box. The user can enter the ID No. within the rich text box and the data will be used as a filter to display the data for that particular ID. But I cannot make it read beyond the first line of the rich text box. If I enter just one ID in the first line, it works perfectly, but if I enter a second ID in the second line, or in the third line, then it will not display anything at all. I tried using for loop to read each line of the rich text box but it doesn't work. Any advice or solution??
here is my code :
namespace TrackCon
{
public partial class trackInput : Form
{
public trackInput()
{
InitializeComponent();
}
/*private void trackInput_Load(object sender, EventArgs e)
{
// TODO: This line of code loads data into the 'trackingBMSDATADataSet.BRDATA' table. You can move, or remove it, as needed.
this.bRDATATableAdapter.Fill(this.trackingBMSDATADataSet.BRDATA);
}*/
private void trackBtn_Click(object sender, EventArgs e)
{
RichTextBox dynamicRichTextBox = new RichTextBox();
DataTable dt = null;
string connoInput = richTextBox1.Text;
string conString = Properties.Settings.Default.BMSDATAConnectionString;
//string[] RichTextBoxLines = dynamicRichTextBox.Lines;
foreach (char line in richTextBox1.Text)
{
using (SqlCeConnection con = new SqlCeConnection(#"Data Source=C:\Documents and Settings\Administrator\My Documents\Visual Studio 2008\Projects\TrackCon\TrackCon\BMSDATA.sdf;Persist Security Info = True;Password=xxxx"))
{
con.Open();
SqlCeCommand com = new SqlCeCommand("SELECT conno,cmpsno,ctrx,dsysdate,cstnno,corigin FROM BRDATA WHERE conno = '" + richTextBox1.Text + "'OR cmpsno = '" + richTextBox1.Text + "'", con);
SqlCeDataAdapter adap = new SqlCeDataAdapter(com);
DataSet set = new DataSet();
adap.Fill(set);
if (set.Tables.Count > 0)
{
dt = set.Tables[0];
}
dataGridView1.DataSource = dt;
con.Close();
}
}
}
}
}

I suggest to use a TextBox and set MultiLine to true.
Then you can read all the ids like this:
string[] ids = myTextBox.Text.Split('\n');
EDIT:
You can use SQL's IN to find all elements:
string sql = "SELECT conno, etc FROM BRDATA WHERE conno IN (" + String.Join(", ", ids) + ")";

Related

Need clarification about how to apply a custom update to data adapter source

I have created a record-view form that contains a few bound elements via a BindingSource and a BindingNavigator. The viewing of the data fields is operating correctly. Note that the variables da and ds are global in this form.
private void frmItem_Load(object sender, EventArgs e) {
string scon = System.Configuration.ConfigurationManager.ConnectionStrings["myitems"].ToString();
da = new SqlDataAdapter("Select * From myitems where id > 0 ", scon);
ds = new DataSet();
da.Fill(ds);
bindingSource1.DataSource = ds.Tables[0];
bindingNavigator1.BindingSource = this.bindingSource1;
this.txtId.DataBindings.Add(new Binding("Text", bindingSource1, "id", true));
this.txtItem.DataBindings.Add(new Binding("Text", bindingSource1, "item", true));
this.txtUpdatedwhen.DataBindings.Add(new Binding("Text", bindingSource1, "updatedwhen", true));
}
I am showing this record-view form from a data grid view of items by using a row header mouse dbl-click event. The requested row from the dgv is correctly being selected and its row data is correctly being shown in the record-view form.
private void dgvItems_RowHeaderMouseDoubleClick(object sender, DataGridViewCellMouseEventArgs e) {
frmItem gfrmItem = new frmItem();
string sID = this.dgvItems.CurrentRow.Cells[0].Value.ToString();
gfrmItem.FilterByID(sID);
gfrmItem.Show();
}
I've added a save button to the navigator so that I can make individual record save. What I'm attempting to do is programatically apply a date/time stamp update before the record is saved from the button click.
private void btnSave_Click(object sender, EventArgs e)
{
this.txtUpdatedwhen.Text = DateTime.Now.ToString();
da.Update(ds);
}
Although the date/time value is changed per the code and shows in the form, the update is not applying the date/time change.
I thought that the textbox value was being bound to the underlying dataset and would accept changes as if I had entered it manually ... but this is not occurring. I had read some other posts that using the data adapter update is the right way to go about this as apposed to doing something like performing a direct sql update.
I'm stumped with how to resolve this. Any pointers would be greatly appreciated.
After letting this sit a while and coming back to it today, I found a resolution.
There was a common misunderstanding at work that I saw in other posts.
That was that the dataadapter does not automatically populate its commands, even if you pass an active connection into the creation step.
So my resolution was to create a global SqlCommandBuilder variable along with the other ones I was using
SqlDataAdapter da;
SqlConnection sc;
SqlCommandBuilder sb;
DataSet ds;
then create the builder object at form load and initialize the update command into a string variable ... which isn't used there after, but the dataadapter commands are now populated.
string scon = System.Configuration.ConfigurationManager.ConnectionStrings["networkadmin"].ToString();
sc = new SqlConnection(scon);
sc.Open();
string sSelect = "Select * From datatable where id > 0 Order By fld1;";
}
this.da = new SqlDataAdapter(sSelect, sc);
sb = new SqlCommandBuilder(da);
// This initiates the commands, though the target var is not used again.
string uCmd = sb.GetUpdateCommand().ToString();
this.ds = new DataSet();
this.da.Fill(this.ds);
Then the update step does work as expected:
this.txtUpdatedwhen.Text = DateTime.Now.ToString();
DataRowView current = (DataRowView)bindingSource1.Current;
current["updatedwhen"] = this.txtUpdatedwhen.Text;
bindingSource1.EndEdit();
this.da.Update(ds);
I hope this helps someone.

How to catch *all* characters sent to Text field from a HID barcode scanner?

I need to capture input from a barcode scanner. Up until now the input has been just simple alphanum text which I have captured in one Text field. I added a ModifyListener to the Text field and am able to see the input arrive. That has worked fine.
I now need to handle a more complex matrix code which contains values for multiple fields. The values are separated by non-printable characters such as RS, GS and EOT (0x1E, 0x1D, 0x04). The complete data stream has a well-defined header and an EOT at the end, so I am hoping that I can detect barcode input as opposed to manual input.
When a barcode is detected, I can use the record separators RS to split the message and insert the values into the relevant Text fields.
However, the standard key handler on the Text controls ignore these non-printable characters and they do not appear in the controls text. This makes it impossible to proceed as planned.
How could I modify these Text fields to accept and store all characters? Or is there an alternative approach I could use?
This is the code I used to handle the barcode stream.
public class Main
{
static StringBuilder sb = new StringBuilder();
public static void main(String[] args)
{
Display d = new Display();
Shell shell = new Shell(d);
shell.setLayout(new FillLayout());
Text text = new Text(shell, 0);
text.addListener(SWT.KeyDown, new Listener()
{
#Override
public void handleEvent(Event e)
{
// only accept real characters
if (e.character != 0 && e.keyCode < 0x1000000)
{
sb.append(e.character);
String s = sb.toString();
// have start and end idents in buffer?
int i = s.indexOf("[)>");
if (i > -1)
{
int eot = s.indexOf("\u0004", i);
if (eot > -1)
{
String message = s.substring(i, eot + 1);
handleMessageHere(message);
// get ready for next message
sb = new StringBuilder();
}
}
}
}
});
shell.open();
while (!shell.isDisposed())
{
if (!d.readAndDispatch())
d.sleep();
}
}

Insert multiple lines of text into a Rich Text content control with OpenXML

I'm having difficulty getting a content control to follow multi-line formatting. It seems to interpret everything I'm giving it literally. I am new to OpenXML and I feel like I must be missing something simple.
I am converting my multi-line string using this function.
private static void parseTextForOpenXML(Run run, string text)
{
string[] newLineArray = { Environment.NewLine, "<br/>", "<br />", "\r\n" };
string[] textArray = text.Split(newLineArray, StringSplitOptions.None);
bool first = true;
foreach (string line in textArray)
{
if (!first)
{
run.Append(new Break());
}
first = false;
Text txt = new Text { Text = line };
run.Append(txt);
}
}
I insert it into the control with this
public static WordprocessingDocument InsertText(this WordprocessingDocument doc, string contentControlTag, string text)
{
SdtElement element = doc.MainDocumentPart.Document.Body.Descendants<SdtElement>().FirstOrDefault(sdt => sdt.SdtProperties.GetFirstChild<Tag>().Val == contentControlTag);
if (element == null)
throw new ArgumentException("ContentControlTag " + contentControlTag + " doesn't exist.");
element.Descendants<Text>().First().Text = text;
element.Descendants<Text>().Skip(1).ToList().ForEach(t => t.Remove());
return doc;
}
I call it with something like...
doc.InsertText("Primary", primaryRun.InnerText);
Although I've tried InnerXML and OuterXML as well. The results look something like
Example AttnExample CompanyExample AddressNew York, NY 12345 or
<w:r xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main"><w:t>Example Attn</w:t><w:br /><w:t>Example Company</w:t><w:br /><w:t>Example Address</w:t><w:br /><w:t>New York, NY 12345</w:t></w:r>
The method works fine for simple text insertion. It's just when I need it to interpret the XML that it doesn't work for me.
I feel like I must be super close to getting what I need, but my fiddling is getting me nowhere. Any thoughts? Thank you.
I believe the way I was trying to do it was doomed to fail. Setting the Text attribute of an element is always going to be interpreted as text to be displayed it seems. I ended up having to take a slightly different tack. I created a new insert method.
public static WordprocessingDocument InsertText(this WordprocessingDocument doc, string contentControlTag, Paragraph paragraph)
{
SdtElement element = doc.MainDocumentPart.Document.Body.Descendants<SdtElement>().FirstOrDefault(sdt => sdt.SdtProperties.GetFirstChild<Tag>().Val == contentControlTag);
if (element == null)
throw new ArgumentException("ContentControlTag " + contentControlTag + " doesn't exist.");
OpenXmlElement cc = element.Descendants<Text>().First().Parent;
cc.RemoveAllChildren();
cc.Append(paragraph);
return doc;
}
It starts the same, and gets the Content Control by searching for it's Tag. But then I get it's parent, remove the Content Control elements that were there and just replace them with a paragraph element.
It's not exactly what I had envisioned, but it seems to work for my needs.

Ajax Popupcontrolextender issues

I have a bizarre problem. I have followed the example here (http://www.4guysfromrolla.com/articles/071107-1.aspx) to display an ajax popup, but it is not working properly.
The problem I have is that the image attributes are not set properly, I checked with Firebug and this is what I get on page 1 after load.
<img src="StyleSheets/magglass.jpg" id="mainContent_TheGrid_MagGlass_0">
Now the bizarre, if I go to page 2, the onmouseover event is set properly for all images and if I come back to page 1, it is set properly too, e.g.
<img src="StyleSheets/magglass.jpg" onmouseover="$find('pce0').showPopup(); " id="mainContent_TheGrid_MagGlass_0">
I stepped through the code and confirmed that the rowcreated event is firing for my grid, for each row
Any Ideas?
My code is slightly different to the example, see below
protected void TheGrid_RowCreated(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
// Programmatically reference the PopupControlExtender
PopupControlExtender pce = e.Row.FindControl("TheGrid_PopupControlExtender") as PopupControlExtender;
// Set the BehaviorID
string behaviorID = string.Concat("pce", e.Row.RowIndex);
pce.BehaviorID = behaviorID;
// Programmatically reference the Image control
Image i = (Image)e.Row.Cells[0].FindControl("MagGlass");
// Add the client-side attributes (onmouseover & onmouseout)
string OnMouseOverScript = string.Format("$find('{0}').showPopup(); ", behaviorID);
i.Attributes.Add("onmouseover", OnMouseOverScript);
}
}
The GetDynamicContent Method is below, which adds the hidepopup method.
[System.Web.Services.WebMethodAttribute(), System.Web.Script.Services.ScriptMethodAttribute()]
public static string GetDynamicContent(string contextKey)
{
GridView MyGrid = (GridView)HttpContext.Current.Session["TheGrid"];
var MyVar = from GridViewRow MyRow in MyGrid.Rows
where MyRow.Cells[MyRow.Cells.Count - 1].Text == contextKey
select MyRow;
//This is the selected row by the user
GridViewRow MyGridRow = MyVar.SingleOrDefault();
//MyGridRow.Cells[3].Text is the log entry.
string MyTable = #"<table class=""PopUpTable""><tr><td><textarea class=""textarea"">"
+ MyGridRow.Cells[3].Text + "</textarea></td>";
//MyGridRow.RowIndex is used to determine the name of popup control for the hidepopup script
MyTable += "<td><button type=\"button\" class=\"PopUpButton\" onclick=\"$find('pce" + MyGridRow.RowIndex.ToString() + "').hidePopup();\">Close</button></td></tr></table>";
return MyTable;
}
This is the pageIndexChanging event
protected void TheGrid_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
TheGrid.PageIndex = e.NewPageIndex;
LoadFromDB();
}
The LoadFromDB method here:
private void LoadFromDB()
{
try
{
LOGDBDataContext LDC = new LOGDBDataContext(ConfigurationManager.ConnectionStrings[Constants.ConnectionStringName].ConnectionString);
string Query = #"DateTimeStamp >= #0 and DateTimeStamp <= #1";
var Tolo = LDC
.Logs
.Where(Query, this.FromCalendar.SelectedDate, this.ToCalendar.SelectedDate)
.OrderBy("DateTimeStamp desc")
.Select("new (LogID, DateTimeStamp, Organization, LogEntry, ServerHostname)");
TheGrid.DataSource = Tolo;
TheGrid.DataBind();
}
catch (Exception ex)
{
//do something here
}
}
Never Mind, found the answer.
Poor Debugging
A poor attempt at
clearing the gridview that was not
invoked by the pagechanging event
Incompetence thy name is yomismo

Word/Office Automation - How to retrieve selected value from a Drop-down form field

I am trying to retrieve the value of all fields in a word document via office automation using c#. The code is shown below however if the field is a drop-down then the value of the range text is always empty even though I know it is populated. If it is a simple text field then I can see the range text. How do I get the selected drop down item? I feel there must be something quite simple that I'm doing wrong...
private void OpenWordDoc(string filename) {
Microsoft.Office.Interop.Word.Application app = new Microsoft.Office.Interop.Word.Application();
Document doc = app.Documents.Open(filename, ReadOnly: true, Visible: false);
foreach (Field f in doc.Fields) {
string bookmarkName = "??";
if (f.Code.Bookmarks.Count > 0) {
bookmarkName = f.Code.Bookmarks[1].Name; // have to start at 1 because it is vb style!
}
Debug.WriteLine(bookmarkName);
Debug.WriteLine(f.Result.Text); // This is empty when it is a drop down field
}
doc.Close();
app.Quit();
}
Aha - If I scan through FormFields instead of Fields then all is good...
foreach (FormField f in doc.FormFields) {
string bookmarkName = "??";
if (ff.Range.Bookmarks.Count > 0) {
bookmarkName = ff.Range.Bookmarks[1].Name; // have to start at 1 because it is vb style!
}
Debug.WriteLine(bookmarkName);
Debug.WriteLine(ff.Result); // This is empty when it is a drop down field
}
Problem solved. Phew.