c# - Gridview Format Field as Phone Number but some results are 4 digit extensions, how to handle? -
so displaying results sql table in gridview. fields phone numbers. specific field may normal 10 digit number, might 4 digit extension. if it's 4 digit number, want @ minimum not put 10 digit formatting on it, @ max i'd prepend , ext: followed data. here have far. not programmer visual studio wizards , google results cobbled together. assistance.
<form id="form1" runat="server"> <div> <asp:gridview id="gridview1" runat="server" datasourceid="sqldatasource1" autogeneratecolumns="false"> <columns> <asp:templatefield headertext="call destination" sortexpression="calldestination"> <edititemtemplate> <asp:textbox id="textbox2" runat="server" text='<%# bind("calldestination") %>'></asp:textbox> </edititemtemplate> <itemtemplate> <asp:label id="label2" runat="server" text='<%# string.format("{0:(###) ###-####}",convert.toint64(databinder.eval (container.dataitem, "calldestination")))%>'></asp:label> </itemtemplate> </asp:templatefield> </columns> </asp:gridview> <asp:sqldatasource id="sqldatasource1" runat="server" connectionstring="<%$ connectionstrings:oncallconnectionstring %>" selectcommand="select [timestamp], [callerid], [accepted], [calldestination] [oncalllog]"></asp:sqldatasource> </div> </form>
you need use rowdatabound
event intercept each row bound grid can determine if phone number 10 digits or 4 digits , handle each value on case-by-case basis, this:
markup:
<asp:gridview id="gridview1" runat="server" datasourceid="sqldatasource1" autogeneratecolumns="false" onrowdatabound="gridview1_rowdatabound">
note: remove text='<%# string.format("{0:(###) ###-####}",convert.toint64(databinder.eval (container.dataitem, "calldestination")))%>'
<asp:label>
in <itemtemplate>
, because format text , set text
property in rowdatabound
event instead of declaratively.
code-behind:
protected void gridview1_rowdatabound(object sender, gridviewroweventargs e) { // interested in each data row, not header or footer, etc. if(e.row.rowtype == datacontrolrowtype.datarow) { // find label2 control in row lable thelabel = (label)e.row.findcontrol("label2"); // make sure control not null if(thelabel != null) { // cast bound object can use extract value datarowview rowview = (datarowview)e.row.dataitem; // value calldestination field in data source string calldestinationvalue = rowview["calldestination"].tostring(); // find out if calldestination 10 digits or 4 digits if(calldestinationvalue.length == 10) { thelabel.text = string.format("{0:(###) ###-####}", convert.toint64(rowview["calldestination"])); } if(calldestinationvalue.length == 4) { thelabel.text = "ext: " + calldestinationvalue; } } } }
Comments
Post a Comment