Method usage on ItemDataBound C# ASP.net - c#

I have a method to use on ItemDataBound;
static void getPhoto() {
Fonksiyonlar vt=new Fonksiyonlar();
DataTable SeriFoto = vt.GetDataTable("select foto from seriFotograf where seriilanID=" + DataBinder.Eval(e.Item.DataItem, "ilan_id") + " and kapak=true" + " order by seriilanID desc");
if (SeriFoto.Rows.Count < 1)
{
DataRow nullPhotoRow;
nullPhotoRow = SeriFoto.NewRow();
nullPhotoRow["foto"] = "0.png";
SeriFoto.Rows.Add(nullPhotoRow);
}
Repeater rptReddedilenFoto = (Repeater)e.Item.FindControl("rptReddedilenFoto");
rptReddedilenFoto.DataSource = SeriFoto;
rptReddedilenFoto.DataBind();
}
But i get an error:
The name 'e' does not exist in the current context
These codes running normally but it doesn't in method.

The simplest, pass the DataGridItem to this method (or GridViewRow if it's a GridView):
static void getPhoto(DataGridItem item) {
DataRowView view = (DataRowView) item.DataItem;
Fonksiyonlar vt=new Fonksiyonlar();
DataTable SeriFoto = vt.GetDataTable("select foto from seriFotograf where seriilanID=" + view["ilan_id"] + " and kapak=true" + " order by seriilanID desc");
if (SeriFoto.Rows.Count < 1)
{
DataRow nullPhotoRow = SeriFoto.NewRow();
nullPhotoRow["foto"] = "0.png";
SeriFoto.Rows.Add(nullPhotoRow);
}
Repeater rptReddedilenFoto = (Repeater)item.FindControl("rptReddedilenFoto");
rptReddedilenFoto.DataSource = SeriFoto;
rptReddedilenFoto.DataBind();
}

Related

Combobox does not showing added items (with if condition)

I have a question regarding combobox. Add first I try to add some items to classTimeComboBox by looping the array and it works. But when I try to combine the foreach looping with if condition and the combobox display nothing inside it. Can someone fix this for me?
Here is my database screenshot
(All table in the database is in "Short Text" type.)
private void classTimeComboBox_SelectedIndexChanged(object sender, EventArgs e)
{
string ClassTime = classTimeComboBox.Text;
string ClassDate = classDateBox.Text;
string[] ClassName = { "CL01", "CL02", "CL03", "CL04", "CL05", "CL06", "CL07", "CL08", "CL09" };
if(classTimeComboBox.SelectedItem.ToString() == "08:00")
{
foreach (string x in ClassName)
{
cnnOleDB.Open();
checkAvailableClassRoom.CommandText = "Select * from Uploads where [ClassDate]='" + ClassDate + "' AND [ClassTime]='" + ClassTime + "' AND [ClassName]='" + x + "';";
checkAvailableClassRoom.Connection = cnnOleDB;
OleDbDataReader readDatabase = checkAvailableClassRoom.ExecuteReader();
if (readDatabase.Read() != true)
{
classNameComboBox.Items.Add(x);
}
else
{
}
cnnOleDB.Close();
}
}
}
The OleDbReader.Read() advances the reader to the next record and the method returns
true if there are more rows; otherwise, false.
So you should change the code, if you expect to have db more than one row, to this:
while (reader.Read())
{
var stringIdx = reader.GetOrdinal("<string Colum to display in combobox>");
classNameComboBox.Items.Add(reader.GetString(stringIdx));
}
If you only expect one row, or don't care about the number of rows you can change the while with the if you have with a small change:
if (readDatabase.Read() == true)
{
classNameComboBox.Items.Add(x);
}

c# equivalent to document.getElementById("ListBox"+i+"Item"+j).selected=true

I've created a dynamic webpage using strictly html, javascript, and MS Access. While it was functional, locally, there were complications deploying it. Since I have ported the data to MySQL and am trying to use Visual Studio's aspx.cs to do much of what the javascript did previously.
I have a screen that populates a dynamic set of rows based on a query result (two rows per record for aesthetics), one of the cells contains a drop down menu(html select/ asp:ListBox).
When I had everything only on javascript, I could create the cell, then create its contents, then set the selected value using:
document.getElementById("StatusDD" + rowCount).value = reader.GetValue(i);
From what I've gathered so far, the rough equivalent is:
ListItem li = StatusDD1.Items.FindByValue(reader.GetValue(i));
li.Selected = true;
However, I cannot simply hardcode StatusDD1 thru StatusDDx (for one, at the beginning my hardcoded set might be larger than the number of records returned, and two eventually the rows returned will be larger than the set of hardcoded values).
So what I did was I created the following function:
protected void setSelected(string selectId, string value)
{
/*Need to put something here to make the following work*/
selectId.Items.FindByValue(value).Selected = true;
}
The selectId being passed in is the name/id of the ListBox and the value is the value coming back from the query.
It's called like:
setSelected("StatusDD" + rowCount, (string)reader.GetValue(i));
If I could, for lack of better phrase, materialize the name created by "StatusDD"+rowCount, I could pass that name in as if I was passing in a ListBox, rather than a string.
Alternatively, if there was a way to select the ListBox from an array where I could do a conditional check WHERE/IF ListBox.Name = selectId, something like the following PseudoCode:
ListBox a = ListBox.NameMatches(selectId);
a.Items.FindByValue(value).Selected = true;
Currently ListBoxes are being created by defining the box in a string and then passing that string into an HtmlTableCell:
HtmlTable myTable = new HtmlTable();
HtmlTableRow newRow;
string cellId;
string cellContents;
int rowCount = 1;
string statusDisabled = "";
while (reader.Read()){
newRow = new HtmlTableRow();
myTable.Rows.Add( newRow );
...
...
cellContents = "<asp:ListBox name='StatusDD" + rowCount + "' id='StatusDD" + rowCount + "' style='width:100%; " + statusDisabled + "' value='" + reader.GetValue(i) + "' onchange='markNeedSave(" + (rowCount + 1) + ")'><asp:ListItem value='0'></asp:ListItem><asp:ListItem value='1'>New</asp:ListItem>....asp:ListBox>";
newRow.Cells.Add(new HtmlTableCell{InnerHtml = cellContents});
}
If it helps, here's how I had it working in javascript:
while (!rs.EOF) {
rowa = table.insertRow(rowCount);
rowa.id = "RECORD" + rowCount + "a";
cell = rowa.insertCell(i + 1);
cell.id = "RECORD" + rowCount + "_CELL" + (i + 1);
for (i = 0; i < 8; i++) {
cell.innerHTML = "<select name='StatusDD" + rowCount + "' id='StatusDD" + rowCount + "' style='width:100%' value='" + rs.fields(i).value + "' onchange='markNeedSave(" + (rowCount + 1) + ")'><option value='NONE'></option><option value='New'>New</option>...</select>";
if (readonly) {
document.getElementById("StatusDD" + rowCount).disabled = true;
}
document.getElementById("StatusDD" + rowCount).value = rs.fields(i).value;
}
...
}
OK, got the ListBox to work, but as I was researching, and when I finally got it to work, I discovered that what I wanted was the DropDownList, not the ListBox, but the same fixes needed to be done in order to get either to work.
I use the following function now:
protected void setSelected(string selectId, string value)
{
PlaceHolder TCS = Page.FindControl("TestingCS") as PlaceHolder;
DropDownList ddl = TCS.FindControl(selectId) as DropDownList;
if (ddl != null)
{
ddl.SelectedValue = value;
ListItem item = ddl.Items.FindByValue(value);
if(item != null)
{ item.Selected = true;}
}
}
Also, for my cell contents that just contain data using the following is fine:
cellContents = "<someString>";
newRow.Cells.Add(new HtmlTableCell{InnerHtml = cellContents});
but for my drop down (or list box) I need to use:
cell = new HtmlTableCell();
newRow.Cells.Add(cell);
DropList = new DropDownList();
DropList.ID = "StatusDD" + rowCount;
DropList.Items.Add(new ListItem("", "0"));
DropList.Items.Add(new ListItem("New", "1"));
...
cell.Controls.Add(DropList);
setSelected(DropList.ID, (string)(reader.GetValue(i)));
A smoother solution:
protected void setSelected(DropDownList ddl, string value)
{
ListItem item = ddl.Items.FindByValue(value);
if (item != null)
{ item.Selected = true; }
}
...
protected void accessRecord()
{
...
DropList = new DropDownList();
DropList.ID = "StatusDD" + rowCount;
DropList.Attributes["onChange"] = "javascript:markNeedSave(" + rowCount + ");";
DropList.Items.Add(new ListItem("", "0"));
DropList.Items.Add(new ListItem("New", "1"));
...
cell.Controls.Add(DropList);
setSelected(DropList,(string)reader.GetValue(i));
}
...
It sounds like the function you're looking for is FindControl. This can be used from the Page, or any parent control you might have created to hold your output.
An example implementation of your setSelected method might look like this:
protected void SetSelected(string selectId, string value)
{
var lb = Page.FindControl(selectId) as ListBox;
if (lb != null)
{
var item = lb.Items.FindByValue(value)
if(item != null)
item.Selected = true;
}
}

Error Occurs at the time of assigning data to DataSource

Below code works the first time - at Page_Load it's working, data showing in the gridview control. But when I add new data to the database and retrieve I get an error.
I put the breakpoint and I checked step-by-step: DataTable dtsent is not null, it has data, but when it comes to gridSent.DataSource=dtsent an error occurs:
NullReferenceException was unhandled by user code
Object reference not set to an instance of an object
public void BindGridSent()
{
try
{
BusinessObject.BusinessObject bogetMS = new BusinessObject.BusinessObject();
bogetMS.UserID = Convert.ToInt32(HttpContext.Current.Session["uid"]);
DataTable dtsent = new DataTable();
dtsent.Columns.Add("msgID");
dtsent.Columns.Add("ToUsername");
dtsent.Columns.Add("msgContent");
dtsent.Columns.Add("msg_sent_date");
dtsent.Columns.Add("fullmsgContent");
DataRow dwsent = null;
DataSet dssent = businssLogicMS.MessageSentList_BAL(bogetMS);
if (dssent.Tables[0].Rows.Count > 0)
{
for (int i = 0; i < dssent.Tables[0].Rows.Count; i++)
{
dwsent = dtsent.NewRow();
string msgID = dssent.Tables[0].Rows[i]["msgID"].ToString();
dwsent["msgID"] = msgID;
//string username=" <b>" + dssent.Tables[0].Rows[i]["ToUsername"].ToString() + "</b> ";
string username = dssent.Tables[0].Rows[i]["ToUsername"].ToString();
dwsent["ToUsername"] = username;
string stmsg = dssent.Tables[0].Rows[i]["msgContent"].ToString();
string message = stmsg.Substring(0, Math.Min(stmsg.Length, 80)) + "...";
string editmsgbody = message.ToString().Replace("<br />", Environment.NewLine);
dwsent["msgContent"] = editmsgbody;
dwsent["fullmsgContent"] = stmsg;
string date = String.Format("{0:MMM dd}", dssent.Tables[0].Rows[i]["msg_sent_date"]);
dwsent["msg_sent_date"] = "<font color='Red'>" + date + "</font>";
dtsent.Rows.Add(dwsent);
}
gridSent.DataSource = dtsent; --- Error Occurs Here
gridSent.DataBind();
}
else
{
dtsent.Rows.Add(dtsent.NewRow());
gridSent.DataSource = dtsent;
gridSent.DataBind();
int columncount = gridSent.Rows[0].Cells.Count;
gridSent.Rows[0].Cells.Clear();
gridSent.Rows[0].Cells.Add(new TableCell());
gridSent.Rows[0].Cells[0].ColumnSpan = columncount;
gridSent.Rows[0].Cells[0].Text = "No Record Found....";
}
}
catch (Exception ex)
{
throw ex;
}
}

I need to rebind in Grid-view after every record completed in for loop process?

I try to import the records from csv and binding into grid.Then every records process for other details. In this case I need to update the UI after every record completed.
WebscrapeSettings objweb = new WebscrapeSettings();
var dtcontact = GetDataTableFromCsv(#"D:\\(1-5) DEN.csv", true);
if (dtcontact.Rows.Count > 0)
{
string starttime = DateTime.Now.ToString();
for (int ic = 0; ic < dtcontact.Rows.Count; ic++)
{
objweb.SearchType = "Company Linked In";
objweb.ContactName = dtcontact.Rows[ic]["Contact"].ToString();
objweb.Location = dtcontact.Rows[ic]["LinkedInLocation"].ToString();
objweb.Title = dtcontact.Rows[ic]["Title"].ToString();
objweb.SearchString = "";
objweb.EmailDomain = "";
objweb.Company = dtcontact.Rows[ic]["Company"].ToString();
string result = "";
var t = WebScrape(objweb);
if (t.Count > 0)
{
foreach (var pair in t)
{
divnormal.InnerHtml = ic + "-" + Thread.CurrentThread.ManagedThreadId + "-" + "<br/> <br/> <br/>" + divnormal.InnerHtml;// +"<br/> <br/> <br/>" + pair.Value;
}
}
//I want to rebind the Grid Here
BindImportfileDetails();
BindImportrecordsdetails(ImportFileID);
}
string endtime = DateTime.Now.ToString();

put data from simpleDB into data gridview

I was trying to retrieve data from Amazon SimpleDB and currently it only displays data in text like domainName: {attribute1, value2} {attribute1, value2}.
How can I show the data in data grid view? My code is as follows:
public static List<String> GetItemByQuery(IAmazonSimpleDB simpleDBClient, string domainName)
{
List<String> Results = new List<String>(); ;
SelectResponse response = simpleDBClient.Select(new SelectRequest()
{
SelectExpression = "Select * from " + domainName
});
String res = domainName + " has: ";
foreach (Item item in response.Items)
{
res = item.Name + ": ";
foreach (Amazon.SimpleDB.Model.Attribute attribute in item.Attributes)
{
res += "{" + attribute.Name + ", " + attribute.Value + "}, ";
}
res = res.Remove(res.Length - 2);
Results.Add(res);
}
return Results;
}
How you an read here:
http://docs.aws.amazon.com/sdkfornet1/latest/apidocs/html/P_Amazon_SimpleDB_Model_SelectResult_Item.htm
your response.Items is
public List<Item> Item { get; set; }
so you should directly use to DataSource of your Grid, set autogenerate column to your grid to start to view the result

Categories