I´m trying to create a custom GridView with additional functionality but I do have problem with PostBack which are "simulated" by "Button2". On every PostBack (after a first DataBinding) the content of one DataRow gets erased until the GridView is fully empty. It has something to do with AddCustomControls() within the PreRender event. But I don´t know how to fix this issue. Does anybody have an idea? Any help would be greatly appreciated.
Maybe the image below describes the behavior better than my words do.
With DataBind() in the OnLoad event and AddCustomControls in the OnDataBound event it worked pretty well. The table stayed exactly the same between PostBacks. But I couldn´t use this "solution" (which is also not very elegant) anymore when I tried to implement the editing of the grid. Logically the edited values within the TextBoxes were overriden by the DataBind() in OnLoad.
Somehow it has to do with "headerTable.Rows.AddAt(1, controlRow);". If I do "headerTable.Rows.Add(controlRow);" which adds the row at the end everything works finde. So the content AFTER this kind of header row get cleared...
Web.config
<configuration>
<system.web>
<compilation debug="true" targetFramework="4.0" />
<pages>
<controls>
<add tagPrefix="asp" assembly="WebApplication11" namespace="WebApplication11"/>
</controls>
</pages>
</system.web>
</configuration>
Default.aspx
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:mightygridview
ID="mightyGridView"
runat="server"
AllowSorting="true"
AllowHiding="true"
AutoGenerateEditButton="false"
OnRowUpdating="mightyGridView_RowUpdating">
</asp:mightygridview>
<br />
<asp:Button ID="Button1" runat="server" Text="Button - Binding" onclick="Button1_Click" />
<asp:Button ID="Button2" runat="server" Text="Button - Nothing" />
</div>
</form>
</body>
</html>
Default.aspx.cs
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
DataTable tbl = new DataTable();
DataRow row;
tbl.Columns.Add("Spalte A");
tbl.Columns.Add("Spalte B");
tbl.Columns.Add("Spalte C");
row = tbl.NewRow();
row[0] = "Spalte A, Zeile 1";
row[1] = "Spalte B, Zeile 1";
row[2] = "Spalte C, Zeile 1";
tbl.Rows.Add(row);
row = tbl.NewRow();
row[0] = "Spalte A, Zeile 2";
row[1] = "Spalte B, Zeile 2";
row[2] = "Spalte C, Zeile 2";
tbl.Rows.Add(row);
row = tbl.NewRow();
row[0] = "Spalte A, Zeile 3";
row[1] = "Spalte B, Zeile 3";
row[2] = "Spalte C, Zeile 3";
tbl.Rows.Add(row);
mightyGridView.DataSource = tbl;
mightyGridView.DataBind();
}
MightyGridView.cs
public class MightyGridView : GridView
{
public MightyGridView()
{
_images = new Dictionary<_imageTypes, string>();
_images.Add(_imageTypes.SortAsc, "data:;base64,iVBORw0KGgoAAAANSUhEUgAAAA0AAAAJCAYAAADpeqZqAAAAAXNSR0IArs4c6QAAAAZiS0dEAP8A/wD/oL2nkwAAAAlwSFlzAAAOwwAADsMBx2+oZAAAAAd0SU1FB9oGEAstLlCBjxcAAABWSURBVBjTY/z45TsDqYCFkYF0wMTAyMiADW/ese8/LjkmbCZt3r73PzKNYRMjAwMDMkZXuHn73v/oalBs2oTDZHRxJph2XBpQNELVMn759pOM0CMDAADRtiJL6bIYOQAAAABJRU5ErkJggg==");
_images.Add(_imageTypes.SortAscActive, "data:;base64,iVBORw0KGgoAAAANSUhEUgAAAA0AAAAJCAYAAADpeqZqAAAAAXNSR0IArs4c6QAAAAZiS0dEAP8A/wD/oL2nkwAAAAlwSFlzAAAOxAAADsQBlSsOGwAAAAd0SU1FB9oHDgckDaeYtVQAAAA1SURBVBjTY/z//z8DqYCJgQyAU5NK2Yb/JGmCacClkYmQDdg0MhHjJHRxJmL8gC7PSLcgBwAAMRqcsjcZIwAAAABJRU5ErkJggg==");
_images.Add(_imageTypes.SortDesc, "data:;base64,iVBORw0KGgoAAAANSUhEUgAAAA0AAAAJCAYAAADpeqZqAAAAAXNSR0IArs4c6QAAAAZiS0dEAP8A/wD/oL2nkwAAAAlwSFlzAAAOwwAADsMBx2+oZAAAAAd0SU1FB9oGEAstDmvvr98AAABhSURBVBjTY/zy7ScDqYCJgQzA8p/hPwMDAwPDpm17/xNS7OflzAix6T8DA8N/BgY/T4gATg2ezowwtUwYErg0IPsJqhmOfdEU+Ho6M6KrwRoQMI2+OGxm/PTlOzmhRzoAADvsH5oZ616EAAAAAElFTkSuQmCC");
_images.Add(_imageTypes.SortDescActive, "data:;base64,iVBORw0KGgoAAAANSUhEUgAAAA0AAAAJCAYAAADpeqZqAAAAAXNSR0IArs4c6QAAAAZiS0dEAP8A/wD/oL2nkwAAAAlwSFlzAAAOxAAADsQBlSsOGwAAAAd0SU1FB9oHDgckFi39fLgAAABBSURBVBjTY/z//z8DqYCJgQzAAmOolG0gaOWdrgBGFJtgAoQ0YDgPl0Z0cSZCCrAa9P//f6xYuXT9f1xyjHQLcgCoNDp3uWsOTwAAAABJRU5ErkJggg==");
_images.Add(_imageTypes.HideColumn, "data:;base64,iVBORw0KGgoAAAANSUhEUgAAAA0AAAAJCAYAAADpeqZqAAAAAXNSR0IArs4c6QAAAAZiS0dEAP8A/wD/oL2nkwAAAAlwSFlzAAAOxAAADsQBlSsOGwAAAAd0SU1FB9oGEAsyFSzQaK0AAADHSURBVBjThZAxCoNQDIbTnsAbCM4eQfAC4uYstCdwFOd2dXNwFZzcxQtI3+bkrIKz4AW+Ln2l7WtpIJB8yf9DIoAAsq4rVVWx77topnMcR6ZpQvdHecS2bXJTSrIsYxgGNE/TFKWU2LZ90MxwvVwvBEFAXdd4nodSis8dQwTI6XTGsiz6vufb3ABd1+G6Lnme4/v+f9E8zziOQ1mWAFIUxbP+KYqiyHCP49gQPb8nIrIsi4Rh+IokSRJp25Y3+OrQNM3XGz7zDsbcHXO0jDwtAAAAAElFTkSuQmCC");
_images.Add(_imageTypes.ShowAllColumns, "data:;base64,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");
}
private enum _imageTypes { SortAsc, SortAscActive, SortDesc, SortDescActive, HideColumn, ShowAllColumns }
private readonly Dictionary<_imageTypes, string> _images;
public new bool AllowSorting { get; set; }
public bool AllowHiding { get; set; }
public override object DataSource
{
get
{
return Page.Session[this.ID + ".DataSource"];
}
set
{
Page.Session[this.ID + ".DataSource"] = value;
base.DataSource = value;
}
}
private void AddCustomControlsRow()
{
if (DataSource != null)
{
if (AllowSorting || AllowHiding)
{
DataTable dataTable = GetDataTableFromDataSource();
if (dataTable.Columns.Count > 0 && dataTable.Rows.Count > 0)
{
if (this.HeaderRow != null && this.HeaderRow.Parent != null)
{
string sortExpression = dataTable.DefaultView.Sort.Replace(" ASC", "").Replace(" DESC", "");
SortDirection sortDirection = dataTable.DefaultView.Sort.EndsWith(" ASC") ? SortDirection.Ascending : SortDirection.Descending;
Table headerTable = (Table)this.HeaderRow.Parent;
GridViewRow controlRow = new GridViewRow(-1, -1, DataControlRowType.Header, DataControlRowState.Normal);
TableCell controlCell;
ImageButton imageButton;
foreach (TableCell cell in this.HeaderRow.Cells)
{
// Sicherstellen, dass es nicht die Spalte mit den Bearbeiten-Buttons ist, welche keine Überschrift enthält.
if (!(cell.Text.Replace(" ", "").Trim().Length > 0))
{
controlCell = new TableCell();
cell.Attributes.Add("style", "border-bottom: 0");
controlCell.Attributes.Add("style", "border-top: 0; text-align: center");
controlRow.Cells.Add(controlCell);
}
else
{
controlCell = new TableCell();
cell.Attributes.Add("style", "border-bottom: 0");
controlCell.Attributes.Add("style", "border-top: 0; text-align: center");
if (AllowSorting)
{
imageButton = new ImageButton();
imageButton.Attributes.Add("data-column-name", cell.Text);
imageButton.Click += new ImageClickEventHandler(SortColumnAscButton_Click);
if (sortExpression == cell.Text && sortDirection == SortDirection.Ascending)
imageButton.ImageUrl = _images[_imageTypes.SortAscActive];
else
imageButton.ImageUrl = _images[_imageTypes.SortAsc];
controlCell.Controls.Add(imageButton);
imageButton = new ImageButton();
imageButton.Attributes.Add("data-column-name", cell.Text);
imageButton.Click += new ImageClickEventHandler(SortColumnDescButton_Click);
if (sortExpression == cell.Text && sortDirection == SortDirection.Descending)
imageButton.ImageUrl = _images[_imageTypes.SortDescActive];
else
imageButton.ImageUrl = _images[_imageTypes.SortDesc];
controlCell.Controls.Add(imageButton);
controlRow.Cells.Add(controlCell);
}
if (AllowHiding)
{
imageButton = new ImageButton();
imageButton.Attributes.Add("data-column-name", cell.Text);
imageButton.Click += new ImageClickEventHandler(HideColumnButton_Click);
imageButton.ImageUrl = _images[_imageTypes.HideColumn];
controlCell.Controls.Add(imageButton);
controlRow.Cells.Add(controlCell);
}
}
}
headerTable.Rows.AddAt(1, controlRow);
}
}
}
}
}
public static DataTable GetDataTableFromIEnumerable(IEnumerable enumerable)
{
DataTable dataTable = new DataTable();
DataRow row;
PropertyInfo[] propertyInfos;
foreach (object obj in enumerable)
{
propertyInfos = obj.GetType().GetProperties();
if (dataTable.Columns.Count == 0)
foreach (PropertyInfo pi in propertyInfos)
dataTable.Columns.Add(pi.Name, pi.PropertyType);
row = dataTable.NewRow();
foreach (PropertyInfo pi in propertyInfos)
{
object value = pi.GetValue(obj, null);
row[pi.Name] = value;
}
dataTable.Rows.Add(row);
}
return dataTable;
}
private DataTable GetDataTableFromDataSource()
{
DataTable dataTable;
if (DataSource is DataTable)
dataTable = (DataTable)DataSource;
else if (DataSource is IEnumerable)
dataTable = GetDataTableFromIEnumerable((IEnumerable)DataSource);
else
throw new NotSupportedException("Typ wird nicht unterstützt.");
return dataTable;
}
protected override void OnInit(EventArgs e)
{
base.OnInit(e);
}
protected override void OnLoad(EventArgs e)
{
// Weg der funktionierte, jedoch mit Editing Probleme macht: OnLoad: DataBind() / OnDataBound: AddCustomControls.
// Das DataBinding überschrieb die geänderten Werte wieder.
base.OnLoad(e);
}
protected override void OnDataBinding(EventArgs e)
{
base.OnDataBinding(e);
}
protected override void OnDataBound(EventArgs e)
{
base.OnDataBound(e);
}
protected override void OnPreRender(EventArgs e)
{
AddCustomControlsRow();
base.OnPreRender(e);
}
protected override void OnUnload(EventArgs e)
{
base.OnUnload(e);
}
protected void SortColumnAscButton_Click(object sender, ImageClickEventArgs e)
{
DataTable dataTable = GetDataTableFromDataSource();
dataTable.DefaultView.Sort = ((ImageButton)sender).Attributes["data-column-name"] + " ASC";
DataSource = dataTable;
DataBind();
}
protected void SortColumnDescButton_Click(object sender, ImageClickEventArgs e)
{
DataTable dataTable = GetDataTableFromDataSource();
dataTable.DefaultView.Sort = ((ImageButton)sender).Attributes["data-column-name"] + " DESC";
DataSource = dataTable;
DataBind();
}
protected void HideColumnButton_Click(object sender, ImageClickEventArgs e)
{
// todo: Improve. Backup zum resetten, etc.
DataTable dataTable = GetDataTableFromDataSource();
dataTable.Columns.Remove(((ImageButton)sender).Attributes["data-column-name"]);
DataSource = dataTable;
DataBind();
}
Moved it to OnRowCreated which is also fired on every PostBack of the life cycle:
protected override void OnRowCreated(GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.Header)
{
if (AllowSorting || AllowHiding)
AddHeaderControls(e.Row);
}
base.OnRowCreated(e);
}
It also fixed the behavior of the sort buttons etc. A click on a (sort) button did not trigger the event because the "binding" in the PreRender is too late to handle the event.
I also changed the AddHeaderControls method a bit, instead of adding a whole row, I add the controls to the cell itself, here is a snippet:
foreach (TableCell cell in row.Cells)
{
// Sicherstellen, dass es nicht die Spalte mit den Bearbeiten-Buttons ist, welche keine Überschrift enthält.
if (cell.Text.Replace(" ", string.Empty).Trim().Length > 0)
{
// Write the Header Text into the cell as a (Literal)Control, because it would be lost otherwise.
cell.Controls.Add(new LiteralControl(cell.Text));
cell.Controls.Add(new LiteralControl("<br />"));
if (AllowSorting)
{
imageButton = new ImageButton();
imageButton.Attributes.Add("data-column-name", cell.Text);
imageButton.Click += new ImageClickEventHandler(SortColumnAscButton_Click);
if (sortExpression == cell.Text && sortDirection == SortDirection.Ascending)
imageButton.ImageUrl = _images[_imageTypes.SortAscActive];
else
imageButton.ImageUrl = _images[_imageTypes.SortAsc];
cell.Controls.Add(imageButton);
imageButton = new ImageButton();
imageButton.Attributes.Add("data-column-name", cell.Text);
imageButton.Click += new ImageClickEventHandler(SortColumnDescButton_Click);
if (sortExpression == cell.Text && sortDirection == SortDirection.Descending)
imageButton.ImageUrl = _images[_imageTypes.SortDescActive];
else
imageButton.ImageUrl = _images[_imageTypes.SortDesc];
cell.Controls.Add(imageButton);
}
if (AllowHiding)
{
imageButton = new ImageButton();
imageButton.Attributes.Add("data-column-name", cell.Text);
imageButton.Click += new ImageClickEventHandler(HideColumnButton_Click);
imageButton.ImageUrl = _images[_imageTypes.HideColumn];
cell.Controls.Add(imageButton);
}
}
}
Related
I have 3 GridViews, each inside a separate tab. Every row in the GridView is associated with a LinkButton, and when it's clicked a MessageBox are popping up, showing the content on that particular row.
The problem is that when the MessageBox pops up the GridView disappears, and when MessageBox is closed GridView then comes back.
This problem doesn't occur if GridView is used without any tabs and is placed outside the TabControl. Here is my code:
protected void Page_Load(object sender, EventArgs e)
{
TabControl TheTabCtrl = new TabControl("InfoTabCtrl");
for (var i = 0; i < 3; i++)
{
GridView newGridView = new GridView();
//generate dynamic id
newGridView.ID = String.Concat("GridView", i);
newGridView.AutoGenerateColumns = false;
newGridView.RowDataBound += new GridViewRowEventHandler(OnRowDataBound);
//if (!this.IsPostBack)
//{
BoundField bfield = new BoundField();
bfield.HeaderText = "Id";
bfield.DataField = "Id";
newGridView.Columns.Add(bfield);
bfield = new BoundField();
bfield.HeaderText = "Name";
bfield.DataField = "Name";
newGridView.Columns.Add(bfield);
TemplateField tfield = new TemplateField();
tfield.HeaderText = "Country";
newGridView.Columns.Add(tfield);
tfield = new TemplateField();
tfield.HeaderText = "View";
newGridView.Columns.Add(tfield);
//}
this.BindGrid(newGridView, i);
string myString = i.ToString();
TabPage BasicPage1 = new TabPage(myString, myString);
BasicPage1.Controls.Add(newGridView);
TheTabCtrl.Tabs.Add(BasicPage1);
}
if (!this.IsPostBack)
{
string value = Request.Form[TheTabCtrl.Id + "_SelectedTab"];
if (!string.IsNullOrEmpty(value))
{
try
{
TheTabCtrl.SelectedTab = TheTabCtrl.Tabs.IndexOf(TheTabCtrl.Tabs.Where(x => x.Id == value).First());
}
catch
{
}
}
}
form1.Controls.Add(TheTabCtrl.GetControl);
}
private void BindGrid(GridView newGridView, int id)
{
string[][,] jaggedArray = new string[3][,]
{
new string[,] { {"John Hammond", "United States"}, {"Mudassar Khan", "India"}, {"Suzanne Mathews", "France"}, {"Robert Schidner", "Russia"} },
new string[,] { {"Zoey Melwick", "New Zeeland"}, {"Bryan Robertson", "England"}, {"Beth Stewart", "Australia"}, {"Amanda Rodrigues", "Portugal"} },
new string[,] { {"Glenda Becker", "Germany"}, {"Despoina Athanasiadis", "Greece"}, {"Alexandra López", "Spain"}, {"David Bouchard", "Canada"} }
};
for (int row = 0; row < jaggedArray.Length; row++)
{
if (id != row) continue;
DataTable dt = new DataTable();
// Share the same headlines
dt.Columns.AddRange(new DataColumn[3] { new DataColumn("Id", typeof(int)),
new DataColumn("Name", typeof(string)),
new DataColumn("Country",typeof(string)) });
for (int pair = 0; pair < jaggedArray[row].Length / 2; pair++)
{
dt.Rows.Add(pair + 1, jaggedArray[row][pair, 0], jaggedArray[row][pair, 1]);
}
string myPage = string.Concat(row, "page");
string myString = row.ToString();
newGridView.DataSource = dt;
newGridView.DataBind();
}//End for Row
}//BindGrid
protected void OnRowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
TextBox txtCountry = new TextBox();
txtCountry.ID = "txtCountry";
txtCountry.Text = (e.Row.DataItem as DataRowView).Row["Country"].ToString();
e.Row.Cells[1].Width = 200;
e.Row.Cells[2].Controls.Add(txtCountry);
LinkButton lnkView = new LinkButton();
lnkView.ID = "lnkView";
lnkView.Text = "View";
lnkView.Click += ViewDetails;
lnkView.CommandArgument = (e.Row.DataItem as DataRowView).Row["Id"].ToString();
e.Row.Cells[3].Controls.Add(lnkView);
}
}
protected void ViewDetails(object sender, EventArgs e)
{
LinkButton lnkView = (sender as LinkButton);
GridViewRow row = (lnkView.NamingContainer as GridViewRow);
string id = lnkView.CommandArgument;
string name = row.Cells[1].Text;
string country = (row.FindControl("txtCountry") as TextBox).Text;
ClientScript.RegisterStartupScript(this.GetType(), "alert", "alert('Id: " + id + " Name: " + name + " Country: " + country + "')", true);
}
So how can I show a MessageBox without GridView disappearing?
I am not able to check or uncheck a Gwt CheckBoxCell . It works fine in Chrome but it doesn't work at all in mozilla . What wrong i am doing ? Please Suggest . When i am selecting selectAllHeader not able to check/uncheck in mozilla though same works in chrome.
DataGridTableRowModel headerRow = dataGridTableRowList.get(0);
E12CommonUtils.printOnConsole("IN createTableComponent================="+ headerRow);
int width = 50;
final MultiSelectionModel<DataGridTableRowModel> multiSelectionModel = new MultiSelectionModel<DataGridTableRowModel>();
this.setSelectionModel(multiSelectionModel,DefaultSelectionEventManager.<DataGridTableRowModel> createCheckboxManager(0));
multiSelectionModel.addSelectionChangeHandler(new SelectionChangeEvent.Handler()
{
public void onSelectionChange(SelectionChangeEvent event)
{
count++;
E12CommonUtils.printOnConsole("Inside select : ");
Set<DataGridTableRowModel> set = multiSelectionModel.getSelectedSet();
Iterator it = set.iterator();
selectedValues = new StringBuffer();
selectedNames = new StringBuffer();
while (it.hasNext())
{
DataGridTableRowModel row = (DataGridTableRowModel) it.next();
E12CommonUtils.printOnConsole("Inside select = "+ row.getCellText(1));
selectedValues.append(row.getCellText(1) + ":");
E12CommonUtils.printOnConsole("AFTER APPENDING selectedValues = "+ row.getCellText(1));
selectedNames.append(row.getCellData(1).getName() + ":");
}
}
});
E12CommonUtils.printOnConsole("IN $$$$$$$$$$$$$$$$$=================135");
final Column<DataGridTableRowModel, Boolean> checkColumn = new Column<DataGridTableRowModel, Boolean>(new E12CheckBoxCell(false, false))
{
#Override
public Boolean getValue(DataGridTableRowModel dataGridTRModel)
{
boolean isSelected = multiSelectionModel.isSelected(dataGridTRModel);
E12CommonUtils.printOnConsole("checkColumn isSelected["+ isSelected + "]\tprotect["+ dataGridTRModel.getCellData(0).isProtect() + "]");
getFieldUpdater().update(0, dataGridTRModel, isSelected); // If commented deselect all works
return isSelected;
}
};
checkColumn.setFieldUpdater(new FieldUpdater<DataGridTableRowModel, Boolean>()
{
#Override
public void update(int idx,DataGridTableRowModel dataGridTRModel,Boolean value)
{
try
{
CellData cellData = dataGridTRModel.getCellData(0);
cellData.setData(String.valueOf(value));
dataGridTRModel.setCellData(0, cellData);
multiSelectionModel.setSelected(dataGridTRModel, value);
}
catch (Exception e)
{
Window.alert("Exception in checkColumn.setFieldUpdater : "+ e.getMessage());
}
}
});
CheckboxCell checkAll = new CheckboxCell();
// E12CheckBoxCell checkAll = new E12CheckBoxCell(false, false);
Header<Boolean> selectAllHeader = new Header<Boolean>(checkAll){
#Override
public Boolean getValue()
{
E12CommonUtils.printOnConsole("IN getValue()=========");
return false;
}
};
selectAllHeader.setUpdater(new ValueUpdater<Boolean>(){
#Override
public void update(Boolean selected)
{
for (DataGridTableRowModel ele : getVisibleItems())
{
E12CommonUtils.printOnConsole("IN update**************");
multiSelectionModel.setSelected(ele, selected);
}
}
});
this.addColumn(checkColumn, selectAllHeader);
this.setColumnWidth(checkColumn, 20, Unit.PX);
for (int i = 1; i < headerRow.getRowData().size(); i++)
{
final int index = i;
final String colName = headerRow.getCellData(index).getName();
width = 25;// TODO
E12CustomColumn column = new E12CustomColumn(index, false);
this.setColumnWidth(column, width + "px");
// Add a selection model to handle user selection.
ResizableHeader<DataGridTableRowModel> header = new ResizableHeader<DataGridTableRowModel>(colName, this, column) {
#Override
public String getValue()
{
return colName;
}
};
// this.addColumn(column, selectAllHeader,header);
// this.addColumn(selectAllHeader, header);
this.addColumn(column, header);
}
dataProvider.addDataDisplay(this);
dataProvider.refresh();
it may be browser compatibility issue - meta tag might help you
<meta http-equiv="X-UA-Compatible" content="IE=Edge,chrome=1">
For more details follow below url -
What does <meta http-equiv="X-UA-Compatible" content="IE=edge"> do?
I have an issue of connecting bluetooth device through mobile and i can able to send bytes as Outputstream but i cant able to retrive print from Evolute impress printer.Please help me how to get the print
Problem:
how to check evolute printer whether its reciving data which i sent.
Main.java
public class Main extends Activity implements Runnable {
protected static final String TAG = "TAG";
private static final int REQUEST_CONNECT_DEVICE = 1;
private static final int REQUEST_ENABLE_BT = 2;
Button mScan, mPrint, mDisc,check;
BluetoothAdapter mBluetoothAdapter;
private UUID applicationUUID = UUID
.fromString("00001101-0000-1000-8000-00805F9B34FB");
private ProgressDialog mBluetoothConnectProgressDialog;
private BluetoothSocket mBluetoothSocket;
BluetoothDevice mBluetoothDevice;
#Override
public void onCreate(Bundle mSavedInstanceState) {
super.onCreate(mSavedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.main);
mScan = (Button) findViewById(R.id.Scan);
check = (Button)findViewById(R.id.check);
mScan.setOnClickListener(new View.OnClickListener() {
public void onClick(View mView) {
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (mBluetoothAdapter == null) {
Toast.makeText(Main.this, "Message1", 2000).show();
} else {
if (!mBluetoothAdapter.isEnabled()) {
Intent enableBtIntent = new Intent(
BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent,
REQUEST_ENABLE_BT);
} else {
ListPairedDevices();
Intent connectIntent = new Intent(Main.this,
DeviceListActivity.class);
startActivityForResult(connectIntent,
REQUEST_CONNECT_DEVICE);
}
}
}
});
mPrint = (Button) findViewById(R.id.mPrint);
mPrint.setOnClickListener(new View.OnClickListener() {
public void onClick(View mView) {
Thread t = new Thread() {
public void run() {
try {
OutputStream os = mBluetoothSocket
.getOutputStream();
String BILL = "";
BILL = "\nInvoice No: ABCDEF28060000005" + " "
+ "04-08-2011\n";
BILL = BILL
+ "-----------------------------------------";
BILL = BILL + "\n\n";
BILL = BILL + "Total Qty:" + " " + "2.0\n";
BILL = BILL + "Total Value:" + " "
+ "17625.0\n";
BILL = BILL
+ "-----------------------------------------\n";
os.write(BILL.getBytes());
//This is printer specific code you can comment ==== > Start
// Setting height
int gs = 29;
os.write(intToByteArray(gs));
int h = 104;
os.write(intToByteArray(h));
int n = 162;
os.write(intToByteArray(n));
// Setting Width
int gs_width = 29;
os.write(intToByteArray(gs_width));
int w = 119;
os.write(intToByteArray(w));
int n_width = 2;
os.write(intToByteArray(n_width));
// Print BarCode
int gs1 = 29;
os.write(intToByteArray(gs1));
int k = 107;
os.write(intToByteArray(k));
int m = 73;
os.write(intToByteArray(m));
String barCodeVal = "ASDFC028060000005";// "HELLO12345678912345012";
System.out.println("Barcode Length : "
+ barCodeVal.length());
int n1 = barCodeVal.length();
os.write(intToByteArray(n1));
for (int i = 0; i < barCodeVal.length(); i++) {
os.write((barCodeVal.charAt(i) + "").getBytes());
}
//printer specific code you can comment ==== > End
} catch (Exception e) {
Log.e("Main", "Exe ", e);
}
}
};
t.start();
}
});
mDisc = (Button) findViewById(R.id.dis);
mDisc.setOnClickListener(new View.OnClickListener() {
public void onClick(View mView) {
if (mBluetoothAdapter != null)
mBluetoothAdapter.disable();
}
});
}// onCreate
#Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
try {
if (mBluetoothSocket != null)
mBluetoothSocket.close();
} catch (Exception e) {
Log.e("Tag", "Exe ", e);
}
}
#Override
public void onBackPressed() {
try {
if (mBluetoothSocket != null)
mBluetoothSocket.close();
} catch (Exception e) {
Log.e("Tag", "Exe ", e);
}
setResult(RESULT_CANCELED);
finish();
}
public void onActivityResult(int mRequestCode, int mResultCode,
Intent mDataIntent) {
super.onActivityResult(mRequestCode, mResultCode, mDataIntent);
switch (mRequestCode) {
case REQUEST_CONNECT_DEVICE:
if (mResultCode == Activity.RESULT_OK) {
Bundle mExtra = mDataIntent.getExtras();
String mDeviceAddress = mExtra.getString("DeviceAddress");
Log.v(TAG, "Coming incoming address " + mDeviceAddress);
mBluetoothDevice = mBluetoothAdapter
.getRemoteDevice(mDeviceAddress);
mBluetoothConnectProgressDialog = ProgressDialog.show(this,
"Connecting...", mBluetoothDevice.getName() + " : "
+ mBluetoothDevice.getAddress(), true, false);
Thread mBlutoothConnectThread = new Thread(this);
mBlutoothConnectThread.start();
// pairToDevice(mBluetoothDevice); This method is replaced by
// progress dialog with thread
}
break;
case REQUEST_ENABLE_BT:
if (mResultCode == Activity.RESULT_OK) {
ListPairedDevices();
Intent connectIntent = new Intent(Main.this,
DeviceListActivity.class);
startActivityForResult(connectIntent, REQUEST_CONNECT_DEVICE);
} else {
Toast.makeText(Main.this, "Message", 2000).show();
}
break;
}
}
private void ListPairedDevices() {
Set<BluetoothDevice> mPairedDevices = mBluetoothAdapter
.getBondedDevices();
if (mPairedDevices.size() > 0) {
for (BluetoothDevice mDevice : mPairedDevices) {
Log.v(TAG, "PairedDevices: " + mDevice.getName() + " "
+ mDevice.getAddress());
}
}
}
public void run() {
try {
mBluetoothSocket = mBluetoothDevice
.createRfcommSocketToServiceRecord(applicationUUID);
mBluetoothAdapter.cancelDiscovery();
mBluetoothSocket.connect();
mHandler.sendEmptyMessage(0);
} catch (IOException eConnectException) {
Log.d(TAG, "CouldNotConnectToSocket", eConnectException);
closeSocket(mBluetoothSocket);
return;
}
}
private void closeSocket(BluetoothSocket nOpenSocket) {
try {
nOpenSocket.close();
Log.d(TAG, "SocketClosed");
} catch (IOException ex) {
Log.d(TAG, "CouldNotCloseSocket");
}
}
private Handler mHandler = new Handler() {
#Override
public void handleMessage(Message msg) {
mBluetoothConnectProgressDialog.dismiss();
Toast.makeText(Main.this, "DeviceConnected", 5000).show();
}
};
public static byte intToByteArray(int value) {
byte[] b = ByteBuffer.allocate(4).putInt(value).array();
for (int k = 0; k < b.length; k++) {
System.out.println("Selva [" + k + "] = " + "0x"
+ UnicodeFormatter.byteToHex(b[k]));
}
return b[3];
}
public byte[] sel(int val) {
ByteBuffer buffer = ByteBuffer.allocate(2);
buffer.putInt(val);
buffer.flip();
return buffer.array();
}
DeviceListActivity
public class DeviceListActivity extends Activity
{
protected static final String TAG = "TAG";
private BluetoothAdapter mBluetoothAdapter;
private ArrayAdapter<String> mPairedDevicesArrayAdapter;
#Override
protected void onCreate(Bundle mSavedInstanceState)
{
super.onCreate(mSavedInstanceState);
requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
setContentView(R.layout.device_list);
setResult(Activity.RESULT_CANCELED);
mPairedDevicesArrayAdapter = new ArrayAdapter<String>(this, R.layout.device_name);
ListView mPairedListView = (ListView) findViewById(R.id.paired_devices);
mPairedListView.setAdapter(mPairedDevicesArrayAdapter);
mPairedListView.setOnItemClickListener(mDeviceClickListener);
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
Set<BluetoothDevice> mPairedDevices = mBluetoothAdapter.getBondedDevices();
if (mPairedDevices.size() > 0)
{
findViewById(R.id.title_paired_devices).setVisibility(View.VISIBLE);
for (BluetoothDevice mDevice : mPairedDevices)
{
mPairedDevicesArrayAdapter.add(mDevice.getName() + "\n" + mDevice.getAddress());
}
}
else
{
String mNoDevices = "None Paired";//getResources().getText(R.string.none_paired).toString();
mPairedDevicesArrayAdapter.add(mNoDevices);
}
}
#Override
protected void onDestroy()
{
super.onDestroy();
if (mBluetoothAdapter != null)
{
mBluetoothAdapter.cancelDiscovery();
}
}
private OnItemClickListener mDeviceClickListener = new OnItemClickListener()
{
public void onItemClick(AdapterView<?> mAdapterView, View mView, int mPosition, long mLong)
{
mBluetoothAdapter.cancelDiscovery();
String mDeviceInfo = ((TextView) mView).getText().toString();
String mDeviceAddress = mDeviceInfo.substring(mDeviceInfo.length() - 17);
Log.v(TAG, "Device_Address " + mDeviceAddress);
Bundle mBundle = new Bundle();
mBundle.putString("DeviceAddress", mDeviceAddress);
Intent mBackIntent = new Intent();
mBackIntent.putExtras(mBundle);
setResult(Activity.RESULT_OK, mBackIntent);
finish();
}
};
}
}
UnicodeFormatter:
public class UnicodeFormatter {
static public String byteToHex(byte b) {
// Returns hex String representation of byte b
char hexDigit[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
'a', 'b', 'c', 'd', 'e', 'f' };
char[] array = { hexDigit[(b >> 4) & 0x0f], hexDigit[b & 0x0f] };
return new String(array);
}
static public String charToHex(char c) {
// Returns hex String representation of char c
byte hi = (byte) (c >>> 8);
byte lo = (byte) (c & 0xff);
return byteToHex(hi) + byteToHex(lo);
}
}
Manifest.xml
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.printapplication"
android:versionCode="1"
android:versionName="1.0" >
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
<uses-permission android:name="android.permission.BLUETOOTH" />
<permission
android:name="android.permission.BLUETOOTH"
android:label="BLUETOOTH" >
</permission>
<permission android:name="android.permission.BLUETOOTH_ADMIN" >
</permission>
<uses-sdk
android:minSdkVersion="15"
android:targetSdkVersion="21" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name=".Main"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".DeviceListActivity"
android:label="#string/app_name" >
</activity>
</application>
</manifest>
I have a custom datagrid which is defined as follows
public class CustomDataGrid<T> extends DataGrid<T> {
private static final int PAGE_SIZE = 10;
public CustomDataGrid(ProvidesKey<T> keysProvider) {
super(PAGE_SIZE, keysProvider);
}
public CustomDataGrid() {
super(PAGE_SIZE);
}
public void redrawRow(int absRowIndex) {
int relRowIndex = absRowIndex - getPageStart();
checkRowBounds(relRowIndex);
setRowData(absRowIndex, Collections.singletonList(getVisibleItem(relRowIndex)));
}
}
I am using ui binder and in my xml file I have defined the elements as follows
<com:CustomDataGrid ui:field="commissionListDataGrid"></com:CustomDataGrid>
Now the custom datagrid is initialised as follows
#UiField
CustomDataGrid commissionListDataGrid;
private final Set<Long> showingFriends = new HashSet<Long>();
private Column<ServiceCategorywiseCommissionDetails, String> viewFriendsColumn;
private Column<ServiceCategorywiseCommissionDetails, String> serviceType;
public ZoneCommissionListView() {
commissionListDataGrid = new CustomDataGrid<ServiceCategorywiseCommissionDetails>(new ProvidesKey<ServiceCategorywiseCommissionDetails>() {
#Override
public Object getKey(ServiceCategorywiseCommissionDetails item) {
return item == null ? null : item.getId();
}
});
commissionListDataGrid.setWidth("100%");
commissionListDataGrid.setEmptyTableWidget(new Label("Empty data"));
commissionListDataGrid.setHeight("100%");
// commissionListLayoutPanel = new SimpleLayoutPanel();
initCommissionListDataGrid();
// commissionListLayoutPanel.add(commissionListDataGrid);
//RootLayoutPanel.get().add(commissionListLayoutPanel);
}
#Override
public Widget asWidget() {
return this.widget;
}
#Override
public void setUiHandlers(ZoneCommissionListUiHandlers uiHandlers) {
this.uiHandlers = uiHandlers;
}
public void initCommissionListDataGrid() {
// View friends.
SafeHtmlRenderer<String> anchorRenderer = new AbstractSafeHtmlRenderer<String>() {
#Override
public SafeHtml render(String object) {
SafeHtmlBuilder sb = new SafeHtmlBuilder();
sb.appendHtmlConstant("(").appendEscaped(object).appendHtmlConstant(")");
return sb.toSafeHtml();
}
};
viewFriendsColumn = new Column<ServiceCategorywiseCommissionDetails, String>(new ClickableTextCell(anchorRenderer)) {
#Override
public String getValue(ServiceCategorywiseCommissionDetails object) {
if (showingFriends.contains(object.getId())) {
return "-";
} else {
return "+";
}
}
};
viewFriendsColumn.setFieldUpdater(new FieldUpdater<ServiceCategorywiseCommissionDetails, String>() {
#Override
public void update(int index, ServiceCategorywiseCommissionDetails object, String value) {
if (showingFriends.contains(object.getId())) {
showingFriends.remove(object.getId());
} else {
showingFriends.add(object.getId());
}
// Redraw the modified row.
commissionListDataGrid.redrawRow(index);
}
});
// First name.
serviceType = new Column<ServiceCategorywiseCommissionDetails, String>(new TextCell()) {
#Override
public String getValue(ServiceCategorywiseCommissionDetails object) {
return object.getServiceType();
}
};
commissionListDataGrid.setTableBuilder(new CustomTableBuilder());
commissionListDataGrid.setHeaderBuilder(new CustomHeaderBuilder());
// commissionListDataGrid.setFooterBuilder(new CustomFooterBuilder());
// GWT.log("list size is " + ContactDatabase.get().getDataProvider().getList().size());
// commissionListDataGrid.setRowData(ContactDatabase.get().getDataProvider().getList());
// Button button = new Button();
// button.setText("hello");
// commissionListLayoutPanel.add(commissionListDataGrid);
this.widget = uiBinder.createAndBindUi(this);
}
private class CustomTableBuilder extends AbstractCellTableBuilder<ServiceCategorywiseCommissionDetails> {
private final String childCell = " ";
private final String rowStyle;
private final String selectedRowStyle;
private final String cellStyle;
private final String selectedCellStyle;
#SuppressWarnings("deprecation")
public CustomTableBuilder() {
super(commissionListDataGrid);
// Cache styles for faster access.
Style style = commissionListDataGrid.getResources().style();
rowStyle = style.evenRow();
selectedRowStyle = " " + style.selectedRow();
cellStyle = style.cell() + " " + style.evenRowCell();
selectedCellStyle = " " + style.selectedRowCell();
}
public void buildRowImpl(ServiceCategorywiseCommissionDetails rowValue, int absRowIndex) {
buildServiceTypeRow(rowValue, absRowIndex, false);
GWT.log("Inside build row impl");
// Display list of friends.
if (showingFriends.contains(rowValue.getId())) {
TableRowBuilder row = startRow();
TableCellBuilder th = row.startTH();
th.text("").endTH();
TableCellBuilder th2 = row.startTH();
th2.text("Service Name").endTH();
TableCellBuilder th3 = row.startTH();
th3.text("SuperZone Commission").endTH();
TableCellBuilder th4 = row.startTH();
th4.text("Zone Commission").endTH();
row.endTR();
List<ServiceCommissionDetails> friends = rowValue.getServiceCommissionDetails();
for (ServiceCommissionDetails friend : friends) {
buildServiceCommissionDetailRow(friend, absRowIndex, true);
}
}
}
#SuppressWarnings("deprecation")
private void buildServiceTypeRow(ServiceCategorywiseCommissionDetails rowValue, int absRowIndex, boolean isFriend) {
GWT.log("inside build service Type row");
SelectionModel<? super ServiceCategorywiseCommissionDetails> selectionModel = commissionListDataGrid.getSelectionModel();
boolean isSelected = (selectionModel == null || rowValue == null) ? false : selectionModel.isSelected(rowValue);
boolean isEven = absRowIndex % 2 == 0;
StringBuilder trClasses = new StringBuilder(rowStyle);
if (isSelected) {
trClasses.append(selectedRowStyle);
}
// Calculate the cell styles.
String cellStyles = cellStyle;
if (isSelected) {
cellStyles += selectedCellStyle;
}
if (isFriend) {
cellStyles += childCell;
}
TableRowBuilder row = startRow();
row.className(trClasses.toString());
/*
* Checkbox column.
*
* This table will uses a checkbox column for selection. Alternatively, you can call dataGrid.setSelectionEnabled(true) to
* enable mouse selection.
*/
TableCellBuilder td = row.startTD();
td.className(cellStyles);
td.style().outlineStyle(OutlineStyle.NONE).endStyle();
td.endTD();
/*
* View friends column.
*
* Displays a link to "show friends". When clicked, the list of friends is displayed below the contact.
*/
td = row.startTD();
td.className(cellStyles);
if (!isFriend) {
td.style().outlineStyle(OutlineStyle.NONE).endStyle();
renderCell(td, createContext(1), viewFriendsColumn, rowValue);
}
td.endTD();
// First name column.
td = row.startTD();
td.className(cellStyles);
td.style().outlineStyle(OutlineStyle.NONE).endStyle();
if (isFriend) {
td.text(rowValue.getServiceType());
} else {
renderCell(td, createContext(2), serviceType, rowValue);
}
td.endTD();
// Last name column.
row.endTR();
}
#SuppressWarnings("deprecation")
private void buildServiceCommissionDetailRow(ServiceCommissionDetails rowValue, int absRowIndex, boolean isFriend) {
GWT.log("inside build service commission detail row");
// Calculate the row styles.
// boolean isSelected = (selectionModel == null || rowValue == null)
// ? false : selectionModel.isSelected(rowValue);
// boolean isEven = absRowIndex % 2 == 0;
StringBuilder trClasses = new StringBuilder(rowStyle);
// if (isSelected) {
// trClasses.append(selectedRowStyle);
// }
// Calculate the cell styles.
String cellStyles = cellStyle;
// cellStyles += selectedCellStyle;
cellStyles += childCell;
TableRowBuilder row = startRow();
row.className(trClasses.toString());
/*
* Checkbox column.
*
* This table will uses a checkbox column for selection. Alternatively, you can call dataGrid.setSelectionEnabled(true) to
* enable mouse selection.
*/
TableCellBuilder td = row.startTD();
td.className(cellStyles);
td.style().outlineStyle(OutlineStyle.NONE).endStyle();
td.endTD();
/*
* View friends column.
*
* Displays a link to "show friends". When clicked, the list of friends is displayed below the contact.
*/
// First name column.
td = row.startTD();
td.className(cellStyles);
td.style().outlineStyle(OutlineStyle.NONE).endStyle();
td.text(rowValue.getServiceName());
td.endTD();
td = row.startTD();
td.className(cellStyles);
td.style().outlineStyle(OutlineStyle.NONE).endStyle();
td.text(rowValue.getSuperZoneCommission());
td.endTD();
td = row.startTD();
td.className(cellStyles);
td.style().outlineStyle(OutlineStyle.NONE).endStyle();
td.text(rowValue.getZoneCommission());
td.endTD();
// Last name column.
row.endTR();
}
}
private class CustomHeaderBuilder extends AbstractHeaderOrFooterBuilder<ServiceCategorywiseCommissionDetails> {
private Header<String> firstNameHeader = new TextHeader("Co mmission List");
public CustomHeaderBuilder() {
super(commissionListDataGrid, false);
setSortIconStartOfLine(false);
}
#Override
protected boolean buildHeaderOrFooterImpl() {
Style style = commissionListDataGrid.getResources().style();
String groupHeaderCell = "Header Cell";
// Add a 2x2 header above the checkbox and show friends columns.
TableRowBuilder tr = startRow();
tr.startTH().colSpan(2).rowSpan(2).className(style.header() + " " + style.firstColumnHeader());
tr.endTH();
/*
* Name group header. Associated with the last name column, so clicking on the group header sorts by last name.
*/
// Get information about the sorted column.
ColumnSortList sortList = commissionListDataGrid.getColumnSortList();
ColumnSortInfo sortedInfo = (sortList.size() == 0) ? null : sortList.get(0);
Column<?, ?> sortedColumn = (sortedInfo == null) ? null : sortedInfo.getColumn();
boolean isSortAscending = (sortedInfo == null) ? false : sortedInfo.isAscending();
// Add column headers.
tr = startRow();
buildHeader(tr, firstNameHeader, serviceType, sortedColumn, isSortAscending, false, false);
tr.endTR();
return true;
}
private void buildHeader(TableRowBuilder out, Header<?> header, Column<ServiceCategorywiseCommissionDetails, ?> column, Column<?, ?> sortedColumn, boolean isSortAscending, boolean isFirst,
boolean isLast) {
// Choose the classes to include with the element.
Style style = commissionListDataGrid.getResources().style();
boolean isSorted = (sortedColumn == column);
StringBuilder classesBuilder = new StringBuilder(style.header());
if (isFirst) {
classesBuilder.append(" " + style.firstColumnHeader());
}
if (isLast) {
classesBuilder.append(" " + style.lastColumnHeader());
}
// if (column.isSortable()) {
// classesBuilder.append(" " + style.sortableHeader());
// }
if (isSorted) {
classesBuilder.append(" " + (isSortAscending ? style.sortedHeaderAscending() : style.sortedHeaderDescending()));
}
// Create the table cell.
TableCellBuilder th = out.startTH().className(classesBuilder.toString());
// Associate the cell with the column to enable sorting of the
// column.
enableColumnHandlers(th, column);
// Render the header.
Context context = new Context(0, 2, header.getKey());
renderSortableHeader(th, context, header, isSorted, isSortAscending);
// End the table cell.
th.endTH();
}
}
public void setCommissionListDataGrid(ListDataProvider<ServiceCategorywiseCommissionDetails> dataProvider) {
GWT.log("inside set commissionListDataGrid size is " + dataProvider.getList().size());
commissionListDataGrid.setRowData(dataProvider.getList());
}
And I have a method in the presenter which calls the method set CommissionListDataGrid and sets its row value.
While doing this the data grid is not displayed. However if i add simplelayoutpanel in the following way in the constructor 'ZoneCommissionListView()'
RootPanel.get().add(commissionListLayoutPanel);
Then the data grid is displayed .What exactly am I missing .Any suggestion would be appreciated
DataGrid requires to be put in a LayoutPanel or Panel that implements
the ProvidesResize interface to be visible.
Source
And the SimpelLayoutPanel which you tested also implements the ProvidesResize Interface.
I had created a datagridview like this
public void gridviewsetup()
{
tbl_Aplication.Columns.Add("1", "Empid");
tbl_Aplication.Columns.Add("2", "Emp no");
tbl_Aplication.Columns.Add("3", "Emp Name");
tbl_Aplication.Columns.Add("4", "Department ");
tbl_Aplication.Columns.Add("5", "Designation");
tbl_Aplication.Columns.Add("6", "Shift");
tbl_Aplication.Columns.Add("7", "Start Time");
tbl_Aplication.Columns.Add("8", "End Time");
tbl_Aplication.Columns.Add("9", "OT");
tbl_Aplication.Columns.Add("10", "Reversed Swipe Out");
tbl_Aplication.RowTemplate.Height = 18;
}
and i had populated a data table to fill the data dgridview
public void filldatagrid()
{
if (cmb_dept.Text.Trim() != "")
{
Datatable employedata = empreg.getallemployeeshiftdetails(int.Parse(cmb_dept.SelectedValue.ToString()), Program.LOCTNPK);
tbl_Aplication.Rows.Clear();
tbl_Aplication.DataSource = null;
for (int i = 0; i < employedata.Rows.Count; i++)
{
tbl_Aplication.Rows.Add();
tbl_Aplication.Rows[i].Cells[1].Value = employedata.Rows[i][0];
tbl_Aplication.Rows[i].Cells[2].Value = employedata.Rows[i][1];
tbl_Aplication.Rows[i].Cells[3].Value = employedata.Rows[i][2];
tbl_Aplication.Rows[i].Cells[4].Value = employedata.Rows[i][3];
tbl_Aplication.Rows[i].Cells[5].Value = employedata.Rows[i][4];
tbl_Aplication.Rows[i].Cells[6].Value = employedata.Rows[i][5];
tbl_Aplication.Rows[i].Cells[7].Value = employedata.Rows[i][6];
tbl_Aplication.Rows[i].Cells[8].Value = employedata.Rows[i][7];
tbl_Aplication.Rows[i].Cells[9].Value = 0;
tbl_Aplication.Rows[i].Cells[10].Value = employedata.Rows[i][7];
}
}
}
now i want to filter data in the datagrid with the designation selected in the combobox without going back to database ,I did it like this but it shows error
private void cmb_designation_SelectedIndexChanged(object sender, EventArgs e)
{
if (desgflag != 0)
{
if (cmb_dept.SelectedValue!=null )
{
// tbl_Aplication.DataSource = employedata;
((DataTable)tbl_Aplication.DataSource).DefaultView.RowFilter = " designationnName like '%" + cmb_dept.Text.Trim() + "%' ";
}
}
}
I had done it
private void cmb_department_SelectedIndexChanged(object sender, EventArgs e)
{
try
{
if (cmb_department.Text.Trim() == "" || cmb_department.Text.Trim() == null)
{
tbl_DestinationData.DataSource = dt;
}
else
{
((DataTable)tbl_DestinationData.DataSource).DefaultView.RowFilter = " Dept like '%" + cmb_department.Text.Trim() + "%' ";
}
}
catch (Exception )
{
throw;
}
}