Export from Control to .xls, .doc, .pdf

I use this one quite often when people refuse to use technology and insist on having a piece of paper in front of their face rather than a computer screen. But I digress...

Just throw this in on a button click or whatever event you wish

protected void excelBtn_Click(object sender, EventArgs e)
{
Response.Clear();
//Change the end of next line to whatever you want the filename to be
Response.AddHeader("content-disposition", "attachment;filename=FileName.xls");
Response.Charset = "";
// If you want the option to open the file without saving then
// comment out the line below
// Response.Cache.SetCacheability(HttpCacheability.NoCache);
//For .doc use application/msword or For .pdf use application/pdf below
Response.ContentType = "application/vnd.xls";
System.IO.StringWriter stringWrite = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite);
//Change the control below to whatever control you want to display in the file
mainGV.RenderControl(htmlWrite);
Response.Write(stringWrite.ToString());
Response.End();
}

ERROR: Failed to enable constraints. One or more rows contain values violating non-null, unique, or foreign-key constraints

I don't think this is really a fix, but all I did was go into the properties on the .xsd file and change the EnforceConstratint = false.

My Search String Manipulation using RegEx, Split, Trim

I needed to grab a string from a textbox and search a Database for any matching results. Here is how I did it.
//Grab the text from the TextBox control
string qTxt = searchTxt.Text;
//Create new string
string strClean = String.Empty;
//Create RegEx to strip out all special characters and replace with blank(space)
Regex reg = new Regex("[A-Za-z0-9]");
strClean = Regex.Replace(qTxt, "[^\\w\\.@-]", " ");
//Trim string to remove unnessesary spaces
string TrimstrClean = strClean.Trim();
//Split string on blank(space)
string[] strSplit = TrimstrClean.Split();
//loop through split string to get individual words
for (int i = 0; i < strSplit.Length; i++)
{
//If string is greater than a length of 2 show words
if (strSplit[i].Length >= 2)
{
//Display individual words
resultLbl.Text += "-" + strSplit[i] + "<br>";
}
}

So a search for something like: Test´s that are fun & 60% Would return:
-Test
-that
-are
-fun
-60

SCOPE_IDENTITY in TableAdapters

6 hours later here is how I got it to insert into another table using Scope_Identity:

Wrote Insert statement in first table which would insert then grab the primary key for use in another table
INSERT INTO Table1 (col1, col2) VALUES (@col1, @col2);
SELECT SCOPE_IDENTITY();


Then in the Visual Studio .xsd file select that insert query and go to properties and change the ExecuteMode to Scalar

Next create another Insert statement into the second table like normal:
INSERT INTO Table2 (id, col1, col2) VALUES (@id, @col1, @col2)

Now in the BLL for Table1 and Table2 (separate files like Table1BLL.cs and Table2BLL.cs). In Table1BLL.cs you will need to add two Adapters to connect to Table1 and Table2 like this:
private TEST_Table1TableAdapter _table1Adapter = null;
protected TEST_Table1TableAdapter Adapter
{
get

{

if (_table1Adapter == null)

_table1Adapter = new TEST_Table1TableAdapter();

return _table1Adapter;

}

}

//To grab stuff from Table2BLL
private TEST_Table2TableAdapter _table2Adapter = null;
protected TEST_Table2TableAdapter Adapter1
{
get

{

if (_table2Adapter == null)

_table2Adapter = new TEST_Table2TableAdapter();

return _table2Adapter;

}

}

After the Insert logic in Table1BLL.cs call the Table2 insert logic like this:
int new_ID = Convert.ToInt32(Adapter.Insert(val1, val2));
int rowsAffected = Adapter1.InsertTable2(new_ID, val1, val2);
return rowsAffected == 1;


Grouping in GridView (sort on one column only)

No idea how or why this works, but this is what I did to group a gridview into categories:

protected override void Render(HtmlTextWriter writer)
{
int sortColumnIndex = -1;

string sortColumnHeaderText = string.Empty;

for (int i = 0; i < GridView1.Columns.Count; i++)

{

if (GridView1.Columns[i].SortExpression.CompareTo("Sort Column Header") == 0)

{

sortColumnIndex = i;

sortColumnHeaderText = GridView1.Columns[i].HeaderText;

break;

}

}


Table gridTable = (Table)GridView1.Controls[0];

string lastValue = string.Empty;

foreach (GridViewRow gvr in GridView1.Rows)

{

string currentValue = gvr.Cells[sortColumnIndex].Text;

if (lastValue.CompareTo(currentValue) !=0)

{

int rowIndex = gridTable.Rows.GetRowIndex(gvr);

GridViewRow sortRow = new GridViewRow(rowIndex, rowIndex, DataControlRowType.DataRow, DataControlRowState.Normal);

TableCell sortCell = new TableCell();

sortCell.ColumnSpan = GridView1.Columns.Count;

sortCell.Text = string.Format("{0}: {1}", sortColumnHeaderText, currentValue);

sortCell.BackColor = System.Drawing.Color.LightGray;

sortCell.ForeColor = System.Drawing.Color.DarkRed;

sortCell.Font.Bold = true;


sortRow.Cells.Add(sortCell);

gridTable.Controls.AddAt(rowIndex, sortRow);


lastValue = currentValue;

}

}

base.Render(writer);

}

Gridview Gridlines white in IE (7)

When viewing the GridView in IE gridlines will always appear white. In FireFox they actually look the color of the border like black or whatever you set. So I set up a class in my css like this:

.myrow td
{
border-bottom: 1px solid #000;
}


Then set in my skin file <RowStyle CssClass="myrow"/>

Alternatively you could add CellSpacing="1" to the GridView and that will show a grey gridline. It looks kind of stupid, especially if you only want horizontal gridlines or some custom styles.

Dynamically add values to NavigateUrl

Initially I had NavigateUrl='MyUrl.aspx?id=<%#Eval("userID")%>'

However when I ran the page it would convert everything to html style and I wouldn't get the correct id. The URL came out looking like this: MyUrl.aspx?id=%3C%#Eval(%22userID%22)%20%%3E

To fix put in the URL like this: NavigateUrl='<%#Eval("userID", "MyJobList.aspx?id={0}") %>'

Along the same lines to do a Hyperlink with a MailTo property from Bound Data: <asp:HyperLink ID="HyperLink2" runat="server" NavigateUrl=´<%# Bind("JobRequestedEmail", "mailto:{0}") %>´>Here is the Link</asp:HyperLink>

ERROR: The value for column ‘Column’ in table ‘tbl’ is DBNull.

Thinking why the hell would it care if a column was NULL, I spent a good few hours scouring the internet for answers. I finally figured it out myself, and it totally makes sense if you aren’t an idiot like me.

When creating the .xsd file in Visual Studio, there is a property for the column called NullValue and it was set to (Throw Exception). I changed it to (Null) and all was well.

I still don’t understand why, if you set up your table to allow nulls on certain columns, the .xsd file would automatically set your column to throw an exception on a null value?!? I guess one of those things I will never understand, hope this helps someone out with the same issue.

Delete confirmation on CommandField

protected void DetailsView1_ItemCreated(object sender, EventArgs e)
{
if (DetailsView1.FooterRow != null)
{
int commandRowIndex = DetailsView1.Rows.Count - 1;
if (commandRowIndex > 0)
{
DetailsViewRow commandRow = DetailsView1.Rows[commandRowIndex];

DataControlFieldCell cell = (DataControlFieldCell)commandRow.Controls[0];
foreach (Control ctl in cell.Controls)
{
LinkButton link = ctl as LinkButton;
if (link != null)
{
if (link.CommandName == "Delete")
{
    link.ToolTip = "Click here to delete";
    link.OnClientClick = "return confirm('Do you really want to delete this user?');";
}
}
}
}
}
}

ERROR: Could not find a property named 'columnName' on the type specified by the DataObjectTypeName

In Design view select the ObjectDataSource that is causing the error and go to properties. Remove whatever is in the DataObjectTypeName.

ERROR: Cannot have multiple items selected in a DropDownList

Insert DropDownList1.ClearSelection();
Before the DropDownList1.Items.FindByValue(value).Selected = true;

LIKE statement in TableAdapter

Must be written like this:
LIKE '%' + @username + '%'
I don't know why but if you don't it won't take the param @username

Maintain Scroll Position on Post Back

Just that:
Set MaintainScrollPositionOnPostBack=true; on Page_Load

Get all Active Directory (DirectoryEntry) Properties

DirectoryEntry entry = new DirectoryEntry("LDAP://domain.com");
entry.AuthenticationType = AuthenticationTypes.Secure;
DirectorySearcher deSearch = new DirectorySearcher(entry);

//Added to show only my user not entire directory
deSearch.Filter = "(&(givenname=Erika))";

SearchResultCollection results = deSearch.FindAll();
foreach (SearchResult srUser in results)
{
try
{
DirectoryEntry de = srUser.GetDirectoryEntry();
foreach (string propertyName in de.Properties.PropertyNames)
{
resultLbl.Text += "Property Name: " + propertyName + " - ";
resultLbl.Text += de.Properties["" + propertyName + ""].Value + "<br>";
}
}
catch (Exception ex)
{
errLbl.Text += ex;
}
}

Convert string to Currency

Thanks to Brent who figured this out, I never would have.

iCurListPrice = "2145";
double x = Double.Parse(iCurListPrice);
x = (x / 100);
price_TB.Text = x.ToString("C");

Check if SQL Type is Null

if (!(Convert.IsDBNull(rdr["column_name"])))
{
int iVal = (int)rdr["column_name"];
}

C# Add selected dropdown value after DataBind

dropDownList1.DataBind();
dropDownList1.Items.Insert(0, new ListItem("Select Below", "0"));

Alternitively using a dropdown populated by a ObjectDataSource:

<asp:DropDownList ID="categories" runat="server" AutoPostBack="True" DataSourceID="categoriesDataSource" DataTextField="CategoryName" DataValueField="CategoryID" EnableViewState="False" AppendDataBoundItems="True">
<asp:ListItem Value="-1"> -- Choose a Category -- </asp:ListItem>
</asp:DropDownList>

Don’t forget to set AppendDataBoundItems=true

DataList without Tables

So the <asp:DataList> seems to always want to put tables in the source code causing all sorts of havoc on your tableless layouts.
I found an easy solution and since I usually forget things and spend hours on Google I am putting it here.
Simply add RepeatLayout="Flow" to your DataList and you will happily enter web 2.0.
<asp:DataList ID="yourDL" runat="server" EnableViewState="false" RepeatLayout="Flow">

I HEART Ternary

This is my new favorite thing:
(condition) ? True result : False result;
Ex. result = tlt == 0 ? <li id='current'>" : "<li>";
I use this a lot in creating nav bars.

Select a link on the right

Feel like contacting me feel free:
eday69@gmail.com